4

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

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。有人可以告诉使用这样的处理程序上传大文件的正确方法是什么吗?

4

2 回答 2

7

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

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

(它为您执行小缓冲区/循环,默认使用 4k 缓冲区,或允许通过重载传递自定义缓冲区大小)

于 2012-05-29T08:41:20.610 回答
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();
 }

编辑:删除 binaryreader

于 2012-05-29T08:44:48.303 回答