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)的功能。

相关内容

热门资讯

推荐一款!aapoker脚本怎... 推荐一款!aapoker脚本怎么用,pokemmo手机辅助软件,一直是有挂(存在有挂)破解侠是真的助...
科普攻略!德州真人透视脚本,h... 科普攻略!德州真人透视脚本,hhpoker可以控制吗,果然有挂(有挂教学)1、实时透视辅助更新:用户...
专业讨论!来玩app 德州 辅... 专业讨论!来玩app 德州 辅助,wepoker新号好一点吗,一直真的有挂(有挂头条)1)免费钻石:...
一分钟快速了解!aapoker... 一分钟快速了解!aapoker透视方法,wejoker透视方法,真是是有挂(有挂教程);1、超多福利...
解密关于!wepoker有人用... 解密关于!wepoker有人用过吗,wepoker怎么开辅助,一贯存在有挂(今日头条)1、首先打开辅...
分享开挂内幕!wepoker新... 分享开挂内幕!wepoker新号好一点吗,德普之星辅助工具如何打开,一贯真的是有挂(有挂详细)1)辅...
终于知道!fishpoker透... 终于知道!fishpoker透视,德扑圈透视,竟然真的有挂(有挂功能)1、完成辅助器v3.3的残局,...
大神推荐!wepoker有没有... 大神推荐!wepoker有没有透视方法,wepoker一直输的号能继续打吗,一贯真的是有挂(有挂总结...
玩家必看科普!aapoker安... 玩家必看科普!aapoker安装包怎么使用,hhpoker软件可以玩吗,确实存在有挂(有挂攻略)1、...
我来向大家传授!德普之星透视,... 我来向大家传授!德普之星透视,wepoker钻石怎么看底牌,都是是真的有挂(有挂方法)进入游戏-大厅...