在Asp.Net Core中增加上传文件大小

117

目前,我正在使用Asp.Net Core和MVC6进行工作,需要上传无限制大小的文件。我已经搜索了解决方案,但仍然没有得到实际答案。

我尝试过这个链接

如果有人有任何想法,请帮忙。

谢谢。


我自己仍在努力弄清楚这个问题,尝试了答案中提供的所有解决方案。你们最终能解决这个问题吗? - undefined
14个回答

2

如果你已经滚动到这里,那说明你已经尝试了以上的解决方案。如果你正在使用最新的NET CORE版本(5.., 6..)并且使用IIS进行托管,请按照以下步骤操作。

  1. Add the web.config file to your project and then add the following code there:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.webServer>
            <security>
                <requestFiltering>
                    <!-- Handle requests up to 1 GB -->
                    <requestLimits maxAllowedContentLength="1073741824" />
                </requestFiltering>
            </security>
        </system.webServer>
    </configuration>
    
  2. Set up the Form Options and IIS Server Options in your Startup.cs file like this:

     services.Configure<IISServerOptions>(options =>
     {
         options.MaxRequestBodySize = int.MaxValue;
     });
    
     services.Configure<FormOptions>(o =>
     {
         o.ValueLengthLimit = int.MaxValue;
         o.MultipartBodyLengthLimit = int.MaxValue; 
         o.MultipartBoundaryLengthLimit = int.MaxValue;
         o.MultipartHeadersCountLimit = int.MaxValue;
         o.MultipartHeadersLengthLimit = int.MaxValue;
         o.BufferBodyLengthLimit = int.MaxValue;
         o.BufferBody = true;
         o.ValueCountLimit = int.MaxValue;
     });
    

1

我试图上传一个大文件,但不知何故该文件未到达控制器操作方法,包括文件参数在内的所有参数仍然是null,就像这样:

[HttpPost]
public async Task<IActionResult> ImportMedicalFFSFile(
    Guid operationProgressID,
    IFormFile file, // <= getting null here
    DateTime lastModifiedDate)
{
    ...
}

解决方法是在操作方法或整个控制器\BaseController中添加[DisableRequestSizeLimit]属性:
[DisableRequestSizeLimit]
public class ImportedFileController : BaseController
{
    ...
}

更多信息请参见:

DisableRequestSizeLimitAttribute类


@GertArnold 好的,没问题!已完成。 - Leniel Maccaferri

0
var myLargeString = "this is a large string that I want to send to the server";

$.ajax({
  type: "POST",
  url: "/MyController/MyAction",
  contentType: "application/json",
  data: JSON.stringify({ largeString: myLargeString }),
  processData: false,
  success: function (data) {
    console.log("Data received from the server: " + data);
  },
  error: function (xhr, status, error) {
  console.log("Error: " + error);
  }
});

1
目前,你的回答不够清晰。请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到更多撰写良好答案的信息。 - Community
这并没有回答问题。你展示的是如何通过HTML发布大字符串。这个问题是关于如何增加ASP.NET Core上传文件的服务器端限制。 - Jeremy Caney

0
我唯一有效的解决方法是修改相关项目的Program.cs文件,具体如下:
var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
  long mb = 1048576;
  options.Limits.MaxRequestBodySize = 150 * mb;
});

var app = builder.Build();
app.Run();

1
感谢您对Stack Overflow社区做出贡献的兴趣。这个问题已经有了相当多的答案,其中包括一个已经得到社区广泛认可的答案。您确定您的方法之前没有被提出过吗?如果是这样,解释一下您的方法与众不同的地方,在什么情况下您的方法可能更好,并且/或者为什么您认为以前的答案不够充分会很有用。您可以编辑您的答案并提供解释吗? - Jeremy Caney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接