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

2020-05-09  本文已影响0人  景行1023

环境相关:

问题:

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

解决方案:

       public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                 .ConfigureKestrel((context, options) =>
                 {
                     options.Limits.MaxRequestBodySize = 1048576000;
                 })
                 .UseStartup<Startup>();
        }
       services.AddMvc();
            services.Configure<FormOptions>(x =>
            {
                x.ValueLengthLimit = int.MaxValue;
                x.MultipartBodyLengthLimit = int.MaxValue;
            });
      // 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}");
            }
            
        }
<?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。

上一篇下一篇

猜你喜欢

热点阅读