FileUpload过滤文件类型

来源:互联网 发布:淘宝店铺装修轮播图 编辑:程序博客网 时间:2024/05/16 14:34
 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();
        }

}

原创粉丝点击