加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET C#OutofMemoryException大文件上载

发布时间:2020-12-16 03:58:33 所属栏目:asp.Net 来源:网络整理
导读:我有以下文件上传处理程序: public class FileUploader : IHttpHandler{ public void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; context.Response.ContentType = "text/html"; context.Response.ContentEncoding = Sy
我有以下文件上传处理程序:

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 + "FilesTempFiles";        
    byte[] buffer = new byte[request.ContentLength];
    using (BinaryReader br = new BinaryReader(request.InputStream))
    {
        br.Read(buffer,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.有人能说出使用这样的处理程序上传大文件的正确方法吗?

解决方法

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读