0 votes
33 views
in jQuery by
How to check file size before uploading using jQuery ?

1 Answer

0 votes
by (3.7k points)

If you want to check the file size in jquery, then must access to file system and as you know that jQuery is client side library. It doesn't provide access to user's system. But good news is the HTML 5 File API specification, some properties of files are accessible at client side and file size is one of them. So the idea is to use the size property and find out the file size. As we know that it is a part of HTML 5 specification so it will only work on modern browsers.

HTML Code for file upload:-
Select file : <input type="file" id="fUpload" />

jQuery Code:- Getting file size in jquery:-
<script type="text/javascript">
$(document).ready(function() {
   $("#fUpload").change(function ()
   {
     var file = $("#fUpload")[0].files[0];
     var fsize = fileSize(file);
     console.log(fsize);
     alert(fsize);

  });
 
 function fileSize(file){
    var iSize = (file.size / 1024);
    if (iSize / 1024 > 1){
        if (((iSize / 1024) / 1024) > 1){
            return (Math.round(((iSize / 1024) / 1024) * 100) / 100); // For GB
        }else{
            return (Math.round((iSize / 1024) * 100) / 100); // For MB
        }
    }else{
        return (Math.round(iSize * 100) / 100); //For KB
    }
        return iSize;
}
});
</script>

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...