在ASP .NET CORE 5中上传大文件需要使用流式传输。以下是实现的步骤:
services.AddControllersWithViews(options =>
{
options.Filters.Add(typeof(MaxFileSizeFilter));
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
services.Configure(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
2.在控制器中添加以下代码:
public async Task UploadLargeFile(IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("File is null or empty.");
}
var folderName = "Upload";
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(folderName, fileName);
var dbPath = fullPath;
using (var stream = new FileStream(fullPath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok(new { dbPath });
}
3.添加过滤器MaxFileSizeFilter:
public class MaxFileSizeFilter : IActionFilter
{
private readonly int _maxFileSize;
public MaxFileSizeFilter()
{
_maxFileSize = 4 * 1024 * 1024 * 1024; //4GB
}
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var httpContext = context.HttpContext;
if (httpContext.Request.ContentLength > _maxFileSize)
{
var result = new ContentResult();
result.StatusCode = (int)HttpStatusCode.RequestEntityTooLarge;
result.Content = $"Maximum allowed file size is {_maxFileSize} bytes.";
context.Result = result;
return;
}
await next();
}
}
通过以上步骤,即可实现ASP .NET CORE 5下上传大文件(超过4GB)的功能。