Search code examples
javascriptc#asp.net-mvchttppostedfilebase

Why does HttpPostedFileBase error out on large files before server side validation gets called?


If I disable client side validation

<add key="ClientValidationEnabled" value="false" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />

and try to upload a file that's around 11 MB which sets the file to a HttpPostedFileBase memeber

    [ValidateFile]
    public HttpPostedFileBase StudentImageFileBase { get; set; }

I can't even get my custom validation code to get called. As soon as I hit the submit button I see this error message. I can get client side to work, but what if it's disabled in the users browser? Am I stuck showing this message to the user? Something isn't right, shouldn't I be able to upload large files? I'm not trying to in my app but I have to combat against it server side right?

enter image description here


Solution

  • Look here again. Add appropriate code to your web.config (1GB for example):

     <system.webServer>
       <security>
          <requestFiltering>
             <requestLimits maxAllowedContentLength="1073741824" />
          </requestFiltering>
       </security>
     </system.webServer>
    
    <configuration>
        <system.web>
            <httpRuntime maxRequestLength="1048576" />
        </system.web>
    </configuration>
    

    Now it should allow uploading files up to 1GB and you can check the size on server side:

    public ActionResult Foo(HttpPostedFileBase file)
    {
      ....
      if(file.ContentLength > 536870912) //512MB
         ....
      ....
    }