3

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...

2 Answers 2

8

The 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.org/en-US/docs/DOM/File#Properties

Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.