How to check file input size with jQuery?

Jimmy picture Jimmy · Oct 21, 2009 · Viewed 323.6k times · Source

I have a form with file upload capabilities and I would like to be able to have some nice client side error reporting if the file the user is trying to upload is too big, is there a way to check against file size with jQuery, either purely on the client or somehow posting the file back to the server to check?

Answer

Felipe Sabino picture Felipe Sabino · Oct 14, 2010

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

For the HTML below

<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