最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - On form submit, check size of files ready to be uploaded? - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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/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.)

发布评论

评论列表(0)

  1. 暂无评论