我正在尝试使用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.
我也添加到我的web.config中:
和