Fileupload使用小结

来源:互联网 发布:淘宝手机端的网址 编辑:程序博客网 时间:2024/06/07 03:17

该控件为用户提供一种从他们的计算机向服务器发送文件的方法
可上载的最大文件大小取决于 MaxRequestLength 配置设置的值。
 <httpRuntime maxRequestLength="10"/>
如果用户试图上载超过最大文件大小的文件,上载就会失败。


if (this.FileUpload1.HasFile)
        {
            int MaxLength = 1024 * 1024;//最大为1M
            string name = this.FileUpload1.FileName;//获取文件的名称如:panjun.doc panjun.gif
            string type = name.Substring(name.LastIndexOf(".") + 1).ToLower();//获取文件的类型
            if (this.FileUpload1.PostedFile.ContentLength > MaxLength)//限定上传大小为1MB
            {
               Response.Write("<script>alert('上传文件的大小超过了1MB的最大容量!请压缩后再上传!')</script>");
                return;
            }
            if (type == "jpg" || type == "bmp" || type == "gif" || type == "png")
            {
                string filepath = MapPath("../upload/img/" + name);
                if (!File.Exists(filepath))
                {
                    this.FileUpload1.SaveAs(filepath);//这个是主要的完成上传的代码
                }
                else
                {
                    Response.Write("<script>alert('文件已存在,请重命名后再上传!')</script>");
                    return;
                }
            }
            else
            {
                Response.Write("<script>alert('你选择的文件格式不符合要求!')</script>");
                return;
            }
        }
        else
        {
            Response.Write("<script>alert('请选择一个图片文件!')</script>");
            return;
        }