I have a form which can have multiple file inputs (one file per input, not multi select).
When I submit the form, how do I get an array of all input[type="file"]
contents and use FileReader to look at the file sizes before they are uploaded, and prevent it if any of the files is too large?
$('#MyForm').submit(function() {
});
I can't figure this out at all from what limited FileReader documentation I can find. Or not get it to work, anyway...
I have a form which can have multiple file inputs (one file per input, not multi select).
When I submit the form, how do I get an array of all input[type="file"]
contents and use FileReader to look at the file sizes before they are uploaded, and prevent it if any of the files is too large?
$('#MyForm').submit(function() {
});
I can't figure this out at all from what limited FileReader documentation I can find. Or not get it to work, anyway...
Share Improve this question edited Dec 6, 2012 at 16:23 j08691 208k32 gold badges269 silver badges280 bronze badges asked Dec 6, 2012 at 16:02 BadHorsieBadHorsie 14.6k31 gold badges126 silver badges195 bronze badges2 Answers
Reset to default 8The problem was the way in which I was trying to select the files from the file input with jQuery. Here are some example solutions:
If you have one file input, and the user can only select a single file:
// Get the file
var file = $('input[type="file"]').get(0).files[0];
// File size, in bytes
var size = file.size;
If you have one file input, with multiple file select:
// Get an array of the files
var files = $('input[type="file"]').get(0).files;
// Loop through files
for (var i=0; file = files[i]; i++) {
// File size, in bytes
var size = file.size;
}
If you have multiple file inputs, with multiple file select:
// Loop through each file input
$('input[type="file"]').each(function(i) {
// Get an array of the files for this input
var files = $(this).get(0).files;
// Loop through files
for (var j=0; file = files[j]; j++) {
// File size, in bytes
var size = file.size;
}
});
Once you have the File object, here are the properties you have access to (apart from size):
https://developer.mozilla/en-US/docs/DOM/File#Properties
You're looking for the size
property:
var anyOversize =
Array.prototype.some.call(document.querySelectorAll('input[type="file"]'), function(fileInput) {
return Array.prototype.some.call(fileInput.files, function(file) {
return file.size > limit;
});
});
(That's the size in bytes, by the way.)