Upload and Validate Large Files in Asp.net

Upload Large Files in ASP.Cyberspace Core

By default, ASP.Cyberspace Core allows you to upload files upwards to 28 MB (approximately) in size. However, at times you desire to deviate from this limit and upload larger files on the server. To raise this limit you lot need to brand a couple of additions to your code. And in that location are a few variations of how that can be done. To that end this commodity discusses these possible approaches to upload large files.

Understanding the problem

Consider a simple file upload page as shown below:

The page allows you to pick a file to be uploaded using a file input field. Clicking on the Upload File push button attempts to upload the file on the server. The razor markup that renders this folio is shown below:

<h1>Upload Large File</h1>  <h2>@ViewData["message"]</h2>  <form asp-controller="Home"        asp-action="Upload"        method="post"          enctype="multipart/form-information">      <input type="file" name="file" />     <br /><br />     <button type="submit">Upload File</push button> </grade>

Notice that the enctype attribute of the <form> element is gear up to multipart/form-information since we want to upload a file. The form POSTs to the Upload() activeness of the HomeController.

The Upload() activeness is shown below:

public IActionResult Upload (IFormFile file,[FromServices] IHostingEnvironment env) {      cord fileName = $"{env.WebRootPath}\\{file.FileName}";      using (FileStream fs = System.IO.File.Create(fileName))     {         file.CopyTo(fs);         fs.Flush();     }      ViewData["message"] =  $"{file.Length} bytes uploaded successfully!";      render View("Index"); }

I won't go into the details of this lawmaking. It basically saves the uploaded file to the wwwroot folder. The uploaded file is received through IFormFile parameter and the IHostingEnvironment is injected in order to compute the physical path of the file.

To understand the problem, run the application and try to upload a file with larger size, say 100 MB.

If you are using IIS Express then you lot will get this error message:

And if you are using Kestrel so the fault message should resemble this:

And then, depending on whether you are hosting under IIS or Kestrel the solution is going to slightly differ. Let'due south encounter how.

Solution for IIS Express

For IIS Express, y'all demand to add spider web.config to your project and add the following markup into it:

<system.webServer>   <security>     <requestFiltering>          <requestLimits maxAllowedContentLength="209715200" />          </requestFiltering>   </security> </system.webServer>

The requestLimits element's maxAllowedContentLength is set to 200 MB. Y'all can change this limit as per your requirement. This will alter the default request length to 200 MB.

Save the project and run the application. You won't get the earlier mistake merely now a new error crops upward every bit shown below:

Now the error revels that there is some limit on the multipart form body. To overcome this limit add together the [RequestFormLimits] attribute on top of the Upload() action as shown below:

[HttpPost]          [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]          public IActionResult Upload(IFormFile file, [FromServices] IHostingEnvironment env) {   ...   ... }

And then, nosotros ready the MultipartBodyLengthLimit property of [RequestFormLimits] to 200 MB.

Now, run the application again. This fourth dimension it will happily upload the file.

The maxAllowedContentLength attribute of <requestLimits> modify the setting for the whole application. What if you don't want that much content length for i or more deportment?

In that case yous can apply [RequestSizeLimit] attribute to override the content length limit. This will be articulate in the adjacent section because the solution for Kestrel uses information technology.

Solution for Kestrel

If y'all are using Kestrel you have the option to modify the request content length settings either at activeness level or at the application level.

To change the settings at the activity level you need to use ii attributes namely [RequestSizeLimit] and [RequestFormLimits]. The [RequestSizeLimit] attribute sets the maximum length of a request in bytes whereas [RequestFormLimits] sets the maximum length for multipart trunk length. The following code shows the Upload() action busy with these attributes:

[HttpPost]          [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]          [RequestSizeLimit(209715200)]          public IActionResult Upload(IFormFile file, [FromServices] IHostingEnvironment env) {   ...   ... }

If you lot wish to set up these limits for the entire application and then modify you you lot need to modify Program.cs and Startup.cs.

Open Program.cs and set the Kestrel limit equally shown below:

public static IWebHostBuilder CreateWebHostBuilder (string[] args) =>     WebHost.CreateDefaultBuilder(args)         .UseStartup<Startup>()                      .UseKestrel(options =>         {             options.Limits.MaxRequestBodySize = 209715200;         });

The in a higher place code sets the MaxRequestBodySize property to 200 MB.

At present open up Startup and write the following lawmaking in the ConfigureServices():

public void ConfigureServices(IServiceCollection services) {     services.AddMvc();                      services.Configure<FormOptions>(x =>     {         x.MultipartBodyLengthLimit = 209715200;     }); }

The above code configures the FormOptions and sets the MultipartBodyLengthLimit property to 200 MB.

If you run the application now, information technology will allow you to upload larger files without any problem.

One more thing before I conclude - there is also [DisableRequestSizeLimit] aspect that disables upper limit on the request size altogether. However, you should use information technology with caution.

That's it for at present! Go on coding!!

caggianotharnii.blogspot.com

Source: http://www.binaryintellect.net/articles/612cf2d1-5b3d-40eb-a5ff-924005955a62.aspx

0 Response to "Upload and Validate Large Files in Asp.net"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel