.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>();
转 https://blog.csdn.net/qq_27337291/article/details/121538852
————————————————
版权声明:本文为CSDN博主「关键我是你林哥啊」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_27337291/article/details/121538852
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)