美文网首页
File Upload上传大文件的限制问题(2020.5.9)

File Upload上传大文件的限制问题(2020.5.9)

作者: 景行1023 | 来源:发表于2020-05-09 16:19 被阅读0次

环境相关:

  • asp.net core 3.1
  • IIS
  • html

问题:

需要通过file upload控件上传大小超过30M的文件到服务器, 因为30M是IIS的默认POST Body大小限制,所以需要手动修改这个限制。

解决方案:

  • 在Asp.net core中的Program.cs里,将CreateWebHostBuilder方法修改如下修改Kestrel服务器的限制
       public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                 .ConfigureKestrel((context, options) =>
                 {
                     options.Limits.MaxRequestBodySize = 1048576000;
                 })
                 .UseStartup<Startup>();
        }
  • 在Asp.net core中的Startup.cs里,在ConfigureServices方法中加入如下方法,修改多文件上传时的大小限制
       services.AddMvc();
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });
  • 在对应的Controller文件(我这里是FilesControleler.cs文件)Post方法头部添加如下说明[DisableRequestSizeLimit],取消对应方法的大小限制
      // POST: api/Files
        [HttpPost]
        [DisableRequestSizeLimit] //就是这句话!
        public IActionResult UploadFile([FromForm(Name = "files")] List<IFormFile> files)
        {
            
            try
            {
                SaveFile(files, Alias);

                return Ok(new { files.Count, Size = SizeConverter(files.Sum(f => f.Length)) });
            }
            catch (Exception exception)
            {
                return BadRequest($"Error: {exception.Message}");
            }
            
        }
  • 在项目根目录添加web.config文件,asp.net core默认是没有这个文件的,自己添加,用来修改IIS服务器对文件大小的限制
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!-- To customize the asp.net core module uncomment and edit the following section. 
  For more info see https://go.microsoft.com/fwlink/?linkid=838655 -->
  <system.webServer>
    <handlers>
      <remove name="aspNetCore" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess">
      <environmentVariables>
        <environmentVariable name="COMPLUS_ForceENC" value="1" />
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
    <security>
      <requestFiltering>
        <!-- This will handle requests up to 1GB -->
        <!--主要就是下面这句,重新设定服务器允许的单次请求大小-->
        <requestLimits maxAllowedContentLength="1048576000" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

OK,这样file upload文件上传大小就被限制在了1G。

相关文章

网友评论

      本文标题:File Upload上传大文件的限制问题(2020.5.9)

      本文链接:https://www.haomeiwen.com/subject/teiknhtx.html