gpt4 book ai didi

c# - 大文件上传时的 ASP.NET C# OutofMemoryException

转载 作者:太空狗 更新时间:2023-10-30 00:15:51 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

关于c# - 大文件上传时的 ASP.NET C# OutofMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com