閱讀885 返回首頁    go 技術社區[雲棲]


FileUpload過濾文件類型

 protected void btnSave_Click(object sender, EventArgs e)
        {
            // 確定文件夾
            string directory = WhichDirectory();
            StringBuilder str = new StringBuilder();

            if(FileUpload1.HasFile)
            {
               // 對上傳文件的類型進行過濾,該處隻能傳壓縮文件(rar或者zip),這種文件在火狐

                 瀏覽器中,叫application/octet-stream
               

                if ((this.FileUpload1.PostedFile.ContentType == "application/x-zip-compressed")

                 || (this.FileUpload1.PostedFile.ContentType == "application/octet-stream"))
                {
                    try
                    {
                        str.AppendFormat("上傳文件名: {0}", FileUpload1.FileName);

                        // 保存文件
                        string thefilepath = string.Format(HttpContext.Current.Server.MapPath(("~/

                         {0}/{1}/") FileUpload1.FileName), "資源", directory);
                        FileUpload1.SaveAs(thefilepath);

                        // 顯示文件的信息
                        str.AppendFormat("<br />正在上傳: {0}", FileUpload1.PostedFile.FileName);
                        str.AppendFormat("<br />文件類型: {0}",

                                                            FileUpload1.PostedFile.ContentType);
                        str.AppendFormat("<br />文件大小: {0}",

                                                           FileUpload1.PostedFile.ContentLength);
                        str.AppendFormat("<br />已上傳文件: {0}",

                                                           FileUpload1.PostedFile.FileName);
                    }
                    catch
                    {
                        str.Append("<br /><br />Error<br /><br />");
                        str.AppendFormat("無法儲存: {0}", FileUpload1.FileName);
                    }
                }
                else
                {
                    lblDisplay.Text = "非壓縮文件無法上傳";
                   
                }
              
            }
            else
            {
                lblDisplay.Text = "無文件上傳";
            }
          
            lblMessage.Text = str.ToString();
        }

}

最後更新:2017-04-02 06:52:25

  上一篇:go linq to xml之增改刪查
  下一篇:go 使用JS禁用瀏覽器後退按鈕