大文件上传到服务器报错的问题

来源:互联网 发布:士官肩章淘宝 编辑:程序博客网 时间:2024/05/18 08:59

最近遇见了个大文件上传到服务器报错的问题;我使用的是FileUpload控件上传的

开始用的是SaveAs()和WebClient的方法,结果本地测试可以上传,一发布的服务器就出错,配置文件也写了<httpRuntime maxRequestLength="2058000" executionTimeout="90000" useFullyQualifiedRedirectUrl="false" requestLengthDiskThreshold="8192"/>但是还是不行,

郁闷了我好几天!

今天突然想到了用文件流上传FileStream

结果还真行了!

代码很简单

1.需要配置web.config里写上限制文件上传的大小就上面的那段代码;

2.在aspx.cs的文件里写:

Boolean IsReady = false;
        if (this.FileUpload1.PostedFile != null && this.FileUpload1.PostedFile.ContentLength > 0)
        {
            string path = this.Server.MapPath(@"Uploads");
            string fileName = Path.GetFileName(this.FileUpload1.PostedFile.FileName);
            int ContentLength = this.FileUpload1.PostedFile.ContentLength;
            int UploadedLength = 0;
            //uploadInfo.ContentLength = this.FileUpload1.PostedFile.ContentLength;
            //uploadInfo.FileName = fileName;
            //uploadInfo.UploadedLength = 0;

            //uploadInfo.IsReady = true;
          
            int bufferSize =1000;
            byte[] buffer = new byte[bufferSize];

            using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                while (UploadedLength < ContentLength)
                {
                    int bytes = this.FileUpload1.PostedFile.InputStream.Read(buffer, 0, bufferSize);
                    fs.Write(buffer, 0, bytes);
                    UploadedLength += bytes;
                }
                IsReady = true;
            }
            if(IsReady)
            {
                Response.Redirect("Default2.aspx");
            }

发布到服务器上后在本地上传大文件就没有错误了!

不过上传速度有点慢:一个400M的文件要传大概2分钟!

 

原创粉丝点击