Bab*_*mes 4 c# asp.net out-of-memory ihttphandler large-files
我有以下文件上传处理程序:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我上传大文件时,这会导致OutOfMemoryException.有人能说出使用这样的处理程序上传大文件的正确方法吗?
无需将文件加载到内存中即可将其写入某处.你应该使用一个小缓冲区(可能是8k),并循环流.或者,使用4.0,该CopyTo方法.例如:
using(var newFile = File.Create(tempPath)) {
request.InputStream.CopyTo(newFile);
}
Run Code Online (Sandbox Code Playgroud)
(它为您执行小缓冲区/循环,默认情况下使用4k缓冲区,或允许通过重载传递自定义缓冲区大小)
| 归档时间: |
|
| 查看次数: |
4347 次 |
| 最近记录: |