On form submit, check size of files ready to be uploaded?

file-upload, filereader, javascript, jquery

Solution

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

Problem

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

Original source