如何计算选定的文件

时间:2012-02-10 18:10:09

标签: javascript jquery html html5

我的表单很简单,输入方式如下:

<input id="my_id" multiple="true" type="file" name="image_name[]" />

现在我有两个问题:

  1. 如何使用jQuery或纯JavaScript计算所选文件?
  2. 我怎样才能限制文件选择,比方说10,因为现在它是无限的?

4 个答案:

答案 0 :(得分:12)

如果input type file,则值array与[{1}} files一起存储,密钥为name

$('input#my_id').change(function(){
    var files = $(this)[0].files;
    if(files.length > 10){
        alert("you can select max 10 files.");
    }else{
        alert("correct, you have selected less than 10 files");
    }
});

小提琴示例:http://jsfiddle.net/nze2B/3/

答案 1 :(得分:1)

纯javascript:

document.getElementById("my_id").addEventListener("change", function() {
    console.log(this.files.length);
});

答案 2 :(得分:-1)

<input multiple="multiple" id="s" type="file" />

要获取所选文件的数量,请使用 element.files.length

let ele =document.getElementById("s");

console.log(ele.files.length); // logs number of files selected

验证


/*
Validates number of files selected
selectedFilesLength - number of files selected - ( ele.files.length )
return true if minimumNumberOfFiles <= selectedFilesLength <= maximumNumberOfFiles
*/
function validate(selectedFilesLength, acceptableLengthRange) {
    return (selectedFilesLength >= acceptableLengthRange[0] && selectedFilesLength <= acceptableLengthRange[1]);
}

// example 1 to 10 files
if(validate(document.getElementById("s").length,[1,10])){
   alert("OK");
}
else{
  alert("Limit exceeded");
}

来源:https://www.thewebblinders.in/programming/article/how-to-validate-number-of-files-selected-javascript-6024

上述网站中提供了一个实时示例

答案 3 :(得分:-1)

使用 vanila js

if(document.getElementById("my_id").files.length > 10){
   console.log("10 files can be uploaded at a time.");                   
}