File size validation using javascript

Below is the function which can be used to validate the file size uploaded through a form. This will work fine in IE.

function chkSize()
{

 if((Math.round(document.getElementById("file1").files[0].size)/(1024*1024)) > 4)
            {
                    alert('Document is not UPLOADED. Maximum file size is restricted to 2MB.Please try again Uploading other document!!');
                      return false;
            }  

}



Some of the browsers may prompt errors like firefox. Below is the updated code which can be used in any browser

function chkSize()
{

 var inputFile = document.getElementById('file1');

 for (var i = 0; i < inputFile .files.length; i++)
 { 
                   
       
             var file = inputFile .files[i];


                        if ('size' in file)
                    {
                     
                               var sz=file.size/(1024*1024);
                     
                                  //RESTRICTING UPLOAD FILE SIZE TO 2MB

                                 if(sz >= 2)
                                 {
                                 alert('Document is not UPLOADED. Maximum file size is restricted to 2MB.Please try again Uploading other document!!');
                               return false;
                                 }
                      
                          }
 }//for

}//function

1 comment:

  1. Thank you, above script very useful for me......
    www.blog.ebarun.tk

    ReplyDelete