Month: April 2013

Limit File Upload size in ASP.NET Web applications

One of the problems in file upload is to check the file size before uploading to the server. It’s been a big problem for web developers to restrict the file upload, if it exceeds the given file size .

Now, we can restrict it before uploading to the server using simple JavaScript snippet. Thanks to latest browsers – Microsoft IE 10+, Chrome 21+, Firefox 15+ for making this happen.

Here is the code to do that –

Code Snippet
  1. <form id="form1" runat="server" enctype="multipart/form-data">
  2.     <div>
  3.         <asp:FileUpload runat="server" ID="fileUpload" />
  4.         <asp:Button runat="server" Text="Submit" OnClientClick="return Validate();" OnClick="FileUpload" />
  5.         <div id="Message"></div>
  6.     </div>
  7.     </form>
  8.     <script type="text/javascript" >
  9.         function Validate() {
  10.             var msg = "";
  11.             var bIsValid = true;
  12.             var uploadedFile = document.getElementById("<%=fileUpload.ClientID %>");
  13.  
  14.             if (uploadedFile.files[0].size > 512000) // greater than 512KB
  15.             {
  16.                 msg += "File Size is limited to 512 KB!";
  17.                 bIsValid = false;
  18.             }
  19.  
  20.             var ext = uploadedFile.value.substr(uploadedFile.value.indexOf(".") + 1, uploadedFile.value.length);
  21.             if (ext != "jpg" || ext != "png") {
  22.                 msg += "You can upload only .jpg or .png images!";
  23.                 bIsValid = false;
  24.             }
  25.             if (!bIsValid) {
  26.                 document.getElementById("Message").innerHTML = msg;
  27.                 return false;
  28.             }
  29.             //On Success
  30.             return true;
  31.         }
  32.     </script>

The above code may fail in browsers which doesn’t support HTML 5 features, so it’s better to validate at server end as well for additional security!

Code Snippet
  1. protected  void FileUpload(object sender, EventArgs e)
  2.       {
  3.           if (fileUpload.PostedFile.ContentLength > 512000)
  4.           {
  5.               return;
  6.           }
  7.       }

 

NOTE: The above JavaScript snippet can be used across the technologies including JSP, PHP etc.,

Happy Web Programming!!!