当我将大文件上传到 ASP.NET Core 中的 Web api 时,运行时会在触发处理和存储上传的函数之前将文件加载到内存中。对于大量上传,这会成为一个问题,因为它既慢又需要更多内存。对于早期版本的 ASP.NET有一些文章 http://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/关于如何禁用请求缓冲,但我无法找到有关如何使用 ASP.NET Core 执行此操作的任何信息。是否可以禁用请求缓冲,这样我的服务器上的内存就不会一直耗尽?
Use the Microsoft.AspNetCore.WebUtilities.MultipartReader
因为它...
可以用最小的缓冲解析任何流。它一次为您提供每个部分的标题和正文,然后您对该部分的正文执行您想要的操作(缓冲、丢弃、写入磁盘等)。
这是一个中间件示例。
app.Use(async (context, next) =>
{
if (!IsMultipartContentType(context.Request.ContentType))
{
await next();
return;
}
var boundary = GetBoundary(context.Request.ContentType);
var reader = new MultipartReader(boundary, context.Request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
// process each image
const int chunkSize = 1024;
var buffer = new byte[chunkSize];
var bytesRead = 0;
var fileName = GetFileName(section.ContentDisposition);
using (var stream = new FileStream(fileName, FileMode.Append))
{
do
{
bytesRead = await section.Body.ReadAsync(buffer, 0, buffer.Length);
stream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
section = await reader.ReadNextSectionAsync();
}
context.Response.WriteAsync("Done.");
});
这是帮助者。
private static bool IsMultipartContentType(string contentType)
{
return
!string.IsNullOrEmpty(contentType) &&
contentType.IndexOf("multipart/", StringComparison.OrdinalIgnoreCase) >= 0;
}
private static string GetBoundary(string contentType)
{
var elements = contentType.Split(' ');
var element = elements.Where(entry => entry.StartsWith("boundary=")).First();
var boundary = element.Substring("boundary=".Length);
// Remove quotes
if (boundary.Length >= 2 && boundary[0] == '"' &&
boundary[boundary.Length - 1] == '"')
{
boundary = boundary.Substring(1, boundary.Length - 2);
}
return boundary;
}
private string GetFileName(string contentDisposition)
{
return contentDisposition
.Split(';')
.SingleOrDefault(part => part.Contains("filename"))
.Split('=')
.Last()
.Trim('"');
}
外部参考
- https://github.com/aspnet/HttpAbstractions/pull/146 https://github.com/aspnet/HttpAbstractions/pull/146
- https://github.com/aspnet/HttpAbstractions https://github.com/aspnet/HttpAbstractions
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)