ASP.NETCORE5上传大文件(超过4GB)如何实现?
创始人
2024-09-17 12:00:23
0

在ASP .NET CORE 5中上传大文件需要使用流式传输。以下是实现的步骤:

  1. 在Startup.cs文件中添加服务配置:
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)的功能。

相关内容

热门资讯

揭幕透视!pokemmo内置修... 揭幕透视!pokemmo内置修改器,微信小程序微乐房间怎么开挂,指南书教程(揭秘有挂)-哔哩哔哩1、...
详情透视!哈糖大菠萝怎么开挂,... 详情透视!哈糖大菠萝怎么开挂,小程序微乐斗地主辅助,练习教程(有挂分享)-哔哩哔哩1、玩家可以在哈糖...
揭露透视!pokemmo手机版... 您好,pokemmo手机版透视脚本这款游戏可以开挂的,确实是有挂的,需要了解加去威信【1367043...
详细透视!we-poker靠谱... 详细透视!we-poker靠谱吗,微乐陕西三代自建房挂,绝活儿教程(有挂秘诀)-哔哩哔哩1、每一步都...
总结透视!xpoker辅助控制... 总结透视!xpoker辅助控制,贵州微乐自建房辅助软件下载,法子教程(竟然有挂)-哔哩哔哩1、玩家可...
详情透视!wepoker手机版... 详情透视!wepoker手机版辅助,手机微信小程序游戏破解器下载,窍门教程(的确有挂)-哔哩哔哩1、...
辅助透视!德普之星辅助工具如何... 辅助透视!德普之星辅助工具如何打开,微信小程序微乐房间有挂吗,指引教程(有挂方法)-哔哩哔哩小薇(辅...
详情透视!wepoker免费脚... 详情透视!wepoker免费脚本,微信小程序游戏破解微乐游戏,方案教程(有挂详情)-哔哩哔哩1、上手...
专业透视!wpk插件辅助,微乐... 专业透视!wpk插件辅助,微乐广西小程序,资料教程(证实有挂)-哔哩哔哩1、操作简单,无需wpk插件...
分享透视!wpk透视是真的假的... 分享透视!wpk透视是真的假的,微信小程序游戏破解器,阶段教程(有挂秘籍)-哔哩哔哩一、wpk透视是...