Is it possible to use jQuery to make sure that the multipart form data that is submitted by a form does not exceed a given size?
-
1Would that include the size of the files to be uploaded? (Because I don't think it can be done in that case.) – Frédéric Hamidi Jun 24 '11 at 12:27
-
same question here - http://stackoverflow.com/questions/307679/using-jquery-restricting-file-size-before-uploading – rtdp Jun 24 '11 at 12:29
-
@Frédéric Hamidi: Yes, I want to make sure that an image file that the user tries to upload is not larger than 5MB. At the moment, I'm checking this on the server after the upload but I was hoping there was a way to check this on the client side so that the server can't get pounded with large unnecessary files - especially if it could be used as part of a malicious attack. – Renard Jun 24 '11 at 12:36
-
I think you have to configure your server to reject large files (using its configuration file, not code, so it can cut the connection before uploading the whole file). The client-side solutions in @rtdp's link above do not work in all browsers. – Frédéric Hamidi Jun 24 '11 at 12:46
3 Answers
Sorry, the standard HTML file input is quite limited. File size is one of the properties you can't get.
Typically, web sites that requires the user to upload a) Big files or b) Many files will take advantage of some code written in Flash or Silverlight, because these framworks can access the file system, read file info and expose to javascript. You can, if set up right, prevent the user from uploading large files (or a large number of files).
At work, we use the Fancyupload project: http://digitarald.de/project/fancyupload/3-0/showcase/photoqueue/
jQuery related, I find this plugin interesting: http://blogs.bigfish.tv/adam/2009/06/14/swfupload-jquery-plugin/

- 5,433
- 2
- 21
- 30
An hellish solution is to build up the request yourself and send it by AJAX. You'll face many problems doing so and I definitively think you shouln't do it. But it's an option.

- 2,255
- 18
- 24
If you want to use jQuery's validate
you can by creating this method:
$.validator.addMethod('filesize', function(value, element, param) {
// param = size (en bytes)
// element = element to validate (<input>)
// value = value of the element (file name)
return this.optional(element) || (element.files[0].size <= param)
});
You would use it:
$('#formid').validate({
rules: { inputimage: { required: true, accept: "png|jpe?g|gif", filesize: 1048576 }
messages: { inputimage: "File must be JPG, GIF or PNG, less than 1MB" }
});

- 8,793
- 4
- 49
- 65