Monday, March 10, 2014

Get file size before upload using jquery

 
 File uploading functionality is generally used by the developers. Before 
uploading file on the server, to know the size of file is a good 
practice. By knowing file size, we can restrict the end user to upload 
large size files on the server since we have limited space on the 
server. We should check uploaded file size on server side as well client
 side. In this article I am going to expose how you can get size of file
 before uploading on client side using JQuery.
 
 
 
  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head>
  3. <title>Get File Size</title>
  4. <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript" > </script>
  5. <script type="text/javascript">
  6. function GetFileSize(fileid) {
  7. try {
  8. var fileSize = 0;
  9. //for IE
  10. if ($.browser.msie) {
  11. //before making an object of ActiveXObject,
  12. //please make sure ActiveX is enabled in your IE browser
  13. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
  14. var objFile = objFSO.getFile(filePath);
  15. var fileSize = objFile.size; //size in kb
  16. fileSize = fileSize / 1048576; //size in mb
  17. }
  18. //for FF, Safari, Opeara and Others
  19. else {
  20. fileSize = $("#" + fileid)[0].files[0].size //size in kb
  21. fileSize = fileSize / 1048576; //size in mb
  22. }
  23. alert("Uploaded File Size is" + fileSize + "MB");
  24. }
  25. catch (e) {
  26. alert("Error is :" + e);
  27. }
  28. }
  29. </script>
  30. </head>
  31. <body>
  32. <form name="upload" action="">
  33. <input type="file" name="fUpload" id="fUpload" />
  34. <input type="button" value="Get File Size" onclick="GetFileSize('fUpload');" />
  35. </form>
  36. </body>
  37. </html> 

Example to get file size before upload in Asp.Net using JQuery

Using above defined function "GetFileSize", we can also get file size in Asp.net also like as :
  1. <form id="form1" runat="server">
  2. <asp:FileUpload ID="fUpload" runat="server" />
  3. <asp:Button ID="btnGetSize" runat="server" Text="Button" OnClientClick="GetFileSize('fUpload');" />
  4. </form>
Above example will work on all browsers including IE, FF, Chrome, Safari, Opera etc.
 

No comments:

Post a Comment