ASP.NET C# OutofMemoryException On Large File Upload

痞子三分冷 提交于 2019-12-03 16:39:45

There is no need to load a file into memory to write it to somewhere. You should be using a small buffer (maybe 8k), and looping over the streams. Or, with 4.0, the CopyTo method. For example:

using(var newFile = File.Create(tempPath)) {
    request.InputStream.CopyTo(newFile);
}

(which does the small-buffer/loop for you, using a 4k buffer by default, or allowing a custom buffer-size to be passed via an overload)

You get an OutOfMemoryException because you load your uploaded file into memory. Avoid this by writing your stream directly to a file.

public void ProcessRequest(HttpContext context)
 {
    const int BufferSize = 4096;    

    HttpRequest request = context.Request;

    context.Response.ContentType = "text/html";
    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    var tempFilePath = Path.GetTempFileName();        

    using (Stream fs = File.OpenWrite(tempFilePath));
    {
        byte[] buffer = new byte[BufferSize];
        int read = -1;
        while(read = request.InputStream.Read(buffer, 0, buffer.Length) > 0)
        {            
             fs.Write(buffer, 0, buffer.Length);             
        }
    }

    context.Response.Write("{\"success\":true}");
    context.Response.End();
 }

edit: removed binaryreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!