.NET Core文件上传

本文基于.NET Core 3.1开发。

1、设置文件上传大小

打开Program.cs文件,添加如下代码:

 webBuilder.UseStartup<Startup>().
                    ConfigureKestrel(options =>
                    {
//设置文件上传大小为int的最大值
                        options.Limits.MaxRequestBodySize = int.MaxValue;
                    });

打开Startup.cs,再ConfigureServices添加如下代码:

  //通过设置即重置文件上传的大小限制
            services.Configure<FormOptions>(o =>
            {
                o.BufferBodyLengthLimit = long.MaxValue;
                o.MemoryBufferThreshold = int.MaxValue;
                o.ValueLengthLimit = int.MaxValue;
                o.MultipartBodyLengthLimit = long.MaxValue;
                o.MultipartBoundaryLengthLimit = int.MaxValue;
                o.MultipartHeadersCountLimit = int.MaxValue;
                o.MultipartHeadersLengthLimit = int.MaxValue;
            });

2、文件上传

编写一个文件包含参数的API,进行文件上传,使用【 [DisableRequestSizeLimit]】特性,解除上传大小限值:

  /// <summary>
        /// 事件上传
        /// </summary>
        /// <param name="file">文件信息</param>
        /// <param name="Id">Id</param>
        /// <returns></returns>
        [HttpPost]
        [DisableRequestSizeLimit]
        public async Task<IActionResult> EventUpload(IFormFile file, int Id)
        {
            if (file == null)
            {
                return Ok(new { code="201",msg= "请上传文件" });
            }
            var fileExtension = Path.GetExtension(file.FileName);
            if (fileExtension == null)
            {
                return Ok(new { code = "201", msg = "文件无后缀信息" });
            }
            long length = file.Length;
            if (length > 1024 * 1024 * 300) //200M
            {
                return Ok(new { code = "201", msg = "上传文件不能超过300M" });
            }
            string Paths = Path.GetFullPath("..");          
            string guid = Guid.NewGuid().ToString();
            string stringPath = Paths + $"BufFile\\OutFiles\\DownLoadFiles\\Video\\{guid}\\";
            string filePath = $"{stringPath}";
            if (!System.IO.Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            var saveName = filePath + file.FileName;
           
            using (FileStream fs = System.IO.File.Create(saveName))
            {
                await file.CopyToAsync(fs);
                fs.Flush();
            }
            return  Ok(new { code = "201", msg = "上传成功" });
        }

3、使用中间件,限值POST请求最大限值

自定义个一个HttpRequestMiddleware中间件

  public class HttpRequestMiddleware
    {
        private readonly RequestDelegate next;
        private IWebHostEnvironment environment;
        private readonly ILogger<HttpRequestMiddleware> _logger;

        public HttpRequestMiddleware(RequestDelegate next, IWebHostEnvironment environment, ILogger<HttpRequestMiddleware> logger)
        {
            this.next = next;
            this.environment = environment;
            _logger = logger;
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                HttpRequest request = context.Request;
                if (request.Method.ToLower().Equals("post"))
                {
                    request.EnableBuffering();
                    Stream stream = request.Body;
                    if (request.ContentLength.Value/1024/1024>=801)
                    {
                        await context.Response.WriteAsync("POST请求数据不得超过801M");
                        return;
                    }
                    await next.Invoke(context);
                }
                await next.Invoke(context);
            }
            catch (Exception ex)
            {
                await HandleError(context, ex);
            }
        }

        private async Task HandleError(HttpContext context, Exception ex)
        {
            context.Response.StatusCode = 500;
            context.Response.ContentType = "text/json;charset=utf-8;";
            string errorMsg = $"错误消息:{ex.Message}{Environment.NewLine}错误追踪:{ex.StackTrace}";
            //无论是否为开发环境都记录错误日志
            _logger.LogError(errorMsg);
            //浏览器在开发环境显示详细错误信息,其他环境隐藏错误信息
            if (environment.IsDevelopment())
            {
                await context.Response.WriteAsync(errorMsg);
            }
            else
            {
                await context.Response.WriteAsync("抱歉,服务端出错了");
            }
        }
    }

Configure中,使用当前中间件

 

app.UseMiddleware<HttpRequestMiddleware>();

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值