ASP.NET C#OutofMemoryException大文件上载

时间:2012-05-29 08:34:44

标签: c# asp.net out-of-memory large-files ihttphandler

我有以下文件上传处理程序:

public class FileUploader : IHttpHandler
{
 public void ProcessRequest(HttpContext context)
 {
    HttpRequest request = context.Request;

    context.Response.ContentType = "text/html";
    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    var tempPath = request.PhysicalApplicationPath + "\\Files\\TempFiles\\";        
    byte[] buffer = new byte[request.ContentLength];
    using (BinaryReader br = new BinaryReader(request.InputStream))
    {
        br.Read(buffer, 0, buffer.Length);
    }
    var tempName = WriteTempFile(buffer, tempPath);
    context.Response.Write("{\"success\":true}");
    context.Response.End();
 }

 public bool IsReusable
 {
    get { return true; }
 }

 private string WriteTempFile(byte[] buffer, string tempPath)
 {
    var fileName = GetUniqueFileName(tempPath);
    File.WriteAllBytes(tempPath + fileName, buffer);
    return fileName;
 }
 private string GetUniqueFileName(string tempPath)
 {
    var guid = Guid.NewGuid().ToString().ToUpper();
    while (File.Exists(tempPath + guid))
    {
        guid = Guid.NewGuid().ToString().ToUpper();
    }
    return guid;
 }
}

当我上传大文件时,这会导致OutOfMemoryException。有人能说出使用这样的处理程序上传大文件的正确方法吗?

2 个答案:

答案 0 :(得分:7)

无需将文件加载到内存中以将其写入某处。您应该使用 small 缓冲区(可能是8k),并循环流。或者,使用4.0,CopyTo方法。例如:

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

(为你做小缓冲/循环,​​默认情况下使用4k缓冲区,或允许通过重载传递自定义缓冲区大小)

答案 1 :(得分:4)

您收到OutOfMemoryException,因为您将上传的文件加载到内存中。 通过将流直接写入文件来避免这种情况。

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();
 }

编辑:删除了二元阅读器