Get Certified on your expert knowledge

Brainbench grant you full access to assessments and certifications covering over 600 skills in demand for today's marketplace.
Visit the site and get certified. Click Here to take some FREE tests.

Tuesday, June 26, 2012

Check whether the file is image and less then 50kb in Jquery

File uploading is a very common feature and It is always a good thing to know that what size of file is end user is uploading at the server. As it is quite possible that you don't want to allow users to upload huge files. So it is better to check the size of file before it actually gets uploaded on server. So in this post, I will show you that how to check file size before uploading using jQuery.

Click here to see the working Demo

HTML structure
We will take an file input with flUpload as id.



Javascript code:
$(document).ready(function() {
   $("#flUpload").change(function ()
   {
    
     var iSize = 0;
     var filename = "";
     if($.browser.msie)
     { 
        /*If browser is IE*/      
        var objFSO = new ActiveXObject("Scripting.FileSystemObject");
        var sPath = $("#flUpload")[0].value;
        var objFile = objFSO.getFile(sPath);
        var iSize = objFile.size;
        filename = objFile.name;
        iSize = iSize/ 1024;
     }
     else{
        iSize = ($("#flUpload")[0].files[0].size / 1024);    
        filename = $("#flUpload")[0].files[0].name;
     }   
   
     var ext = (" " + filename + " ").match(/([^\s]+(?=\.(jpg|gif|png))\.\2)/gm);   
     var ext = 1
     if(ext)
     {
        iSize = (Math.round(iSize * 100) / 100);   
        $("#lblSize").html("");
        if (iSize > 50)
        {
            alert("Please select the file less then 50kb");
        }
        else
        {
            $("#lblSize").html( iSize  + "kb");
        }
     }
    else{
        alert("Please select the proper image File");
    }   
  });
});


1 comment: