Using jQuery, Restricting File Size Before Uploading Using jQuery, Restricting File Size Before Uploading javascript javascript

Using jQuery, Restricting File Size Before Uploading


This is a copy from my answers in a very similar question: How to check file input size with jQuery?


You actually don't have access to the filesystem (for example reading and writing local files). However, due to the HTML5 File API specification, there are some file properties that you do have access to, and the file size is one of them.

For this HTML:

<input type="file" id="myFile" />

try the following:

//binds to onchange event of your input field$('#myFile').bind('change', function() {  //this.files[0].size gets the size of your file.  alert(this.files[0].size);});

As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/


Old browsers support

Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it


I don't think it's possible unless you use a flash, activex or java uploader.

For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.


I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.

<img id="myImage" src="" style="display:none;"><br><button onclick="findSize();">Image Size</button><input type="file" id="loadfile" /><input type="button" value="find size" onclick="findSize()" /><script type="text/javascript">function findSize() {    if ( $.browser.msie ) {       var a = document.getElementById('loadfile').value;           $('#myImage').attr('src',a);           var imgbytes = document.getElementById('myImage').size;           var imgkbytes = Math.round(parseInt(imgbytes)/1024);           alert(imgkbytes+' KB');    }else {           var fileInput = $("#loadfile")[0];           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.           var imgkbytes = Math.round(parseInt(imgbytes)/1024);                   alert(imgkbytes+' KB');     }}    </script>

Add Jquery library also.