Asp.Net - Restricting File Upload Size Client Side

So the problem I encountered was that the site would throw an ugly "maxAllowedContentLength exceeded" error when a user would try to upload a file beyond a certain size.  One of the difficulties with this is that the error is thrown before it even gets to an event, so you cannot try to handle it there. One solution that worked locally for me was to modify the web.config in two places, I will link that page below.  Too bad for me that solution did not work on the server for some unknown reason.  I had also tried handling it in the global.asax, but DNN, our CMS, is somehow preventing that from working.  I will link that too below.  So then I turned to a client side way of restricting it.
   The way the client side restriction works is that it uses a newer functionality of html5 that allows most browsers to get the file size.   Older browsers will not work with this, but at this point I am fed up with this and DNN. Also if they disable Javascript they can upload files larger, but how will the site would even work without Javascript is unknown, but probably not very well.

 <script>

     function setUploadButtonState() {

         var maxFileSize = 20480000 // 20MB -> 20000 * 1024, unit is bytes
         var fileUpload = $('#FileUpload1');

         if (fileUpload.val() == '') {
             return false;
         }
         else {
             if (fileUpload[0].files[0].size < maxFileSize) {
                 $('#btnUploadFile').show();
                 $('#lblWarningMessage').text('')
                 return true;
             } else {
                 $('#btnUploadFile').hide();
                 $('#lblWarningMessage').text('Your file is too large, uploaded files must be less than 20MB in size.')
                 return false;
             }
         }
     }

 </script>

And put this as a validator that will fire the function to check the file size upon upload.

 <asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="FileUpload1" ClientValidationFunction="setUploadButtonState();" />

References
First reference is the one I ended up using with the client side restriction.
http://stackoverflow.com/questions/3094748/asp-net-check-file-size-before-upload

Second reference has information about simply allowing larger files. but that would also give you chance to handle it in an event.
http://stackoverflow.com/questions/3853767/maximum-request-length-exceeded?rq=1

Third and fourth reference would allow an application Error event to handled within the global.asax file.
http://www.codeproject.com/Articles/228879/Global-asax-in-ASP-NET
http://stackoverflow.com/questions/665453/catching-maximum-request-length-exceeded

Comments

Popular posts from this blog

Asp.net Publishing Broke Site - "App_WebReferences is not allowed because the application is precompiled"

Telerik - Custom Group Footers In RadGrid