我正在使用 ASP.NET Web Api 2.2 通过以下方式上传文件:
[HttpPost]
public async Task<IHttpActionResult> Post()
{
/* read the content */
var contentTypeHeader = Request.Content.Headers.ContentType;
var contentLength = Request.Content.Headers.ContentLength;
/* Here I get the exception if the file is > 60/70 MB */
var filesProvider = await Request.Content.ReadAsMultipartAsync();
var fileContents = filesProvider.Contents.FirstOrDefault();
var headers = fileContents.Headers;
Stream fileStream = await fileContents.ReadAsStreamAsync();
// ... code not related to this question
}
我已经按如下方式设置了 web.config,以便接受最多 1GB 数据的文件:
<system.web>
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
</system.web>
和
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
但我仍然得到这个异常。异常具有以下结构:
An error occurred System.IO.IOException: Error writing MIME multipart body part to output stream. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
↵ at System.IO.MemoryStream.set_Capacity(Int32 value)
↵ at System.IO.MemoryStream.EnsureCapacity(Int32 value)
↵ at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
↵ at System.IO.MemoryStream.WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
因此,在我看来它像是一个 .NET 异常,与我的代码无关。但是,如何使用 MultiPart 上传大文件呢?
最佳答案
确保首次上传图像文件的虚拟目录(“~/uploads”目录如下例)物理存在。
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);
关于c# - Request.Content.ReadAsMultipartAsync() 和 OutOfMemory 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41223185/