我正在尝试使用asp.net web api实现一个文件上传系统,我遇到了一个问题.我正在尝试将多部分表单数据写入内存流,因此可以根据服务层实现将其写入磁盘或Blob存储.问题是小文件可以正常工作,但是我正在尝试上传一个291 MB的文件,并且会丢失内存异常.这是代码:
if (!Request.Content.IsMimeMultipartContent()) { Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType,"Request must be multipart."); } var provider = new MultipartMemoryStreamProvider(); try { await Request.Content.ReadAsMultipartAsync(provider); var infoPart = provider.Contents.Where(x => x.Headers.ContentDisposition.Name.Replace("\"",string.Empty) == "fileInfo").SingleOrDefault(); var filePart = provider.Contents.Where(x => x.Headers.ContentDisposition.Name.Replace("\"",string.Empty) == "filePart" && x.Headers.ContentDisposition.FileName != null).Single(); byte[] file = null; using (Stream stream = filePart.ReadAsStreamAsync().Result) { using (MemoryStream memory = new MemoryStream()) { stream.CopyTo(memory); file = memory.ToArray(); } } string fileContentType = filePart.Headers.ContentType.MediaType; FileDto result = _fileService.AddFileToResource(Variables); string uri = Url.Link("DefaultGet",new { id = result.ID }); return Request.CreateResponse(HttpStatusCode.OK);
抛出错误的部分是在
await Request.Content.ReadAsMultipartAsync(provider);
确切的错误是
Error writing MIME multipart body part to output stream.
内部例外
Exception of type 'System.OutOfMemoryException' was thrown.
我已经尝试创建一个自定义的BufferPolicySelector,如本帖子how to upload a large file with ASP.NET MVC4 Web Api with progressbar的第二个答案和许多其他地方所示,但这似乎没有什么帮助.
我也添加到我的web.config中:
<httpRuntime targetFramework="4.5" maxRequestLength="307200"/>
和
<security> <requestFiltering> <requestLimits maxAllowedContentLength="367001600"/> </requestFiltering> </security>
解决方法
一个解决方案是使用MultipartFormDataStreamProvider而不是MultipartMemoryStreamProvider来避免在调用期间内存不足的异常
Request.Content.ReadAsMultipartAsync(..)
在为大型文件(> 100 MB)读取MultiPart文件内容时,我尝试使用MemoryStreamProvider时遇到类似的问题.为我工作的工作是使用MultipartFormDataStreamProvider.在ReadAsMultipartAsync调用期间,该文件将写入磁盘,如果在内存中需要它,可以稍后加载该文件.
这是一个例子:
Sending HTML Form Data in Web API: File Upload and Multipart MIME
string root = HttpContext.Current.Server.MapPath("~/App_Data"); var provider = new MultipartFormDataStreamProvider(root); try { // Read the form data. await Request.Content.ReadAsMultipartAsync(provider); // This illustrates how to get the file names. foreach (MultipartFileData file in provider.FileData) { Trace.WriteLine(file.Headers.ContentDisposition.FileName); Trace.WriteLine("Server file path: " + file.LocalFileName); } return Request.CreateResponse(HttpStatusCode.OK); } catch(...)