Javascript – Using jQuery, Restricting File Size Before Uploading

imagejavascriptjqueryjquery-pluginsupload

On PHP, they have a way to restrict file size AFTER uploading, but not BEFORE uploading. I use the Malsup jQuery Form Plugin for my form posting, and it supports image file posting.

I was wondering if perhaps there's a restriction where I can set how many bytes can pass through that AJAX stream up to the server? That could permit me to check that file size and return an error if the file is too big.

By doing this on the client side, it blocks those newbies who take a 10MB photo shot from their Pentax and try to upload that.

Best Answer

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