Thursday, February 21, 2013

How to validate the File Size using JQuery


As the IE is not supporting the HTML 5 File API then what is the solution to check the file size. Well, with IE you can use FileSystem ActiveX object to get the file size. But the problem with latest IE versions (7,8 and 9) is that by default they don't allow ActiveX objects from security reason perspective. If you want to run this, then you have to explicitly allow ActiveX object by changing the settings of IE.

To allow ActiveX -> Go to Tools->Internet Options-> Security->Custom Level->Choose Enable or Prompt ActiveX.

But this is not a perfect solution as you can't ask your end-users to do these kind of settings. Hope that IE 10 will support the HTML 5 API.

So the complete code looks like below code. It first checks if browser is IE or not. If it's IE then using ActiveX object gets the file size. If not then get the file size using HTML 5 API.
$(document).ready(function() {
   $("#flUpload").change(function () 
   { 
     var iSize = 0;
     if($.browser.msie)
     {
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var sPath = $("#flUpload")[0].value;
        var objFile = objFSO.getFile(sPath);
        var iSize = objFile.size;
        iSize = iSize/ 1024;
     }
     else
        iSize = ($("#flUpload")[0].files[0].size / 1024); 

     if (iSize / 1024 > 1) 
     { 
        if (((iSize / 1024) / 1024) > 1) 
        { 
            iSize = (Math.round(((iSize / 1024) / 1024) * 100) / 100);
            $("#lblSize").html( iSize + "Gb"); 
        }
        else
        { 
            iSize = (Math.round((iSize / 1024) * 100) / 100)
            $("#lblSize").html( iSize + "Mb"); 
        } 
     } 
     else 
     {
        iSize = (Math.round(iSize * 100) / 100)
        $("#lblSize").html( iSize  + "kb"); 
     }    
  }); 
});
//Code Ends

No comments:

Post a Comment