Monday, 22 July 2013

Checking A File's Upload Size In The Browser

This really just a quick note so I don't lose the code snippet I just used...

I'm working on a form which allows users to upload a file, but we want to stop them uploading giant things. Ultimately the server's maximum upload filesize will stop anything too huge getting through, but it's nice to remind people of the limit before they bother uploading.

This is a great little snippet to do that in current versions of Chrome, Firefox and Safari.

$('#contact_file').bind('change', function() { 
  filebytes = this.files[0].size;
  if(filebytes>1024*1024*5) {
    alert("The file you selected is TOO LARGE and will be rejected by the server. Please select a smaller file."); 
  }
});

If you can't work out what is happening there, then "contact_file" is the id from your file input and 1024*1024*5 is the limit you want to impose, in this case 5MB. Don't forget to check that the server side limit is in line with this.

It won't work in IE* or some older browser versions, but it's a nice extra courtesy for users where it can be executed. You could also hook it up to the submit button if you want to do a check at that stage.

*Apparently there's an ActiveX thing you can do for IE users, but I am not so inclined.

No comments:

Post a Comment