Friday, July 24, 2015

ASP.NET MVC Upload Large Files

I recently had to setup a website that required uploading huge files ranging from a few MBs to a few GBs. If you have come across this problem, you'll see that the control never reaches the Controller (pun not intended!) when uploading anything over 304 MB. Turns out ASP.NET requires the Web.Config file to be updated with the following -

  1. maxRequestLength attribute - This attribute tells ASP.NET engine the maximum length of the request (duh!). This goes in the httpRuntime tag of your system.web file. The httpRuntime tag should already be present in your Web.Config, so just look it up and add the maxRequestLength attribute in there. For example -
    <system.web> <httpRuntime targetFramework="4.5" maxRequestLength="2147483647"/> </system.web>
    It is set in KB and is set to 4096KB. .
  2. maxAllowedContentLength attribute - This attribute tells ASP.NET engine the maximum content length (again duh!). This also goes in the Web.Config file, but in the requestLimits tag under requestFiltering under security tags in system.webServer. This might not be already present in your Web.Config file so just copy paste the below underlined code under the system.webServer tag -

    <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer>
    It is set in Bytes. .

And that's it. Now you can upload those huge files without any problems. A few things to note -
  1. The number in the maxRequestLength attribute is in KB (KiloBytes) but the number in the maxAllowedContentLength attribute is in Bytes.
  2. In cases when the sizes mentioned in maxRequestLength and maxAllowedContentLength attrbutes differ, ASP.NET engine will use the smaller one.
  3. The sizes are in unsigned integers, so they do have an upper limit.
  4. This is probably off topic but remember to not use functions like "ReadToEnd()" for reading files.

1 comment: