具有多个文件上载字段的HTML表单,如何检查客户端的最大文件大小

时间:2022-06-11 20:40:29

I have this simple script that checks max file size client side in a html form. The check works for the first file added, but I'm having a struggle finding out how to apply the method for checking the other input fields as they are dynamically added.

我有这个简单的脚本,以html格式检查最大文件大小客户端。检查适用于添加的第一个文件,但我很难找到如何应用该方法来检查动态添加的其他输入字段。

The check is based on var uploadField = document.getElementById("file1");

检查基于var uploadField = document.getElementById(“file1”);

Check out this fiddle to better understand the issue: http://jsfiddle.net/tZPg4/16341/

看看这个小提琴,以便更好地理解这个问题:http://jsfiddle.net/tZPg4/16341/

Any tips on how to solve this would be much appreciated.

任何有关如何解决这个问题的提示都将非常感激。

2 个解决方案

#1


1  

You'll need to delegate for objects that are dynamically added. In your code, use this instead of addressing file1 specifically

您需要委托动态添加的对象。在您的代码中,使用它而不是专门处理file1

$("#files").delegate("input","change",function(){
        if(this.files[0].size > 2000000){
                alert('File is larger than 2MB. Please choose a smaller file');
       this.value = "";
    };
});

#2


1  

Do a check for total number of File Input items and validate. Updated http://jsfiddle.net/zz8c9c9u/5/

检查文件输入项的总数并进行验证。更新了http://jsfiddle.net/zz8c9c9u/5/

#1


1  

You'll need to delegate for objects that are dynamically added. In your code, use this instead of addressing file1 specifically

您需要委托动态添加的对象。在您的代码中,使用它而不是专门处理file1

$("#files").delegate("input","change",function(){
        if(this.files[0].size > 2000000){
                alert('File is larger than 2MB. Please choose a smaller file');
       this.value = "";
    };
});

#2


1  

Do a check for total number of File Input items and validate. Updated http://jsfiddle.net/zz8c9c9u/5/

检查文件输入项的总数并进行验证。更新了http://jsfiddle.net/zz8c9c9u/5/