jquery在提交之前验证文件类型和文件大小

问题描述:


可能重复:

使用jQuery,在上传前限制文件大小

在将文件上传到服务器之前,是否有一个好的jquery脚本或其他方法可以验证文件大小和文件类型?我试过看了一遍但从来没有找到任何可以做这样的事情。

Is there a good jquery script or other method that can verify file size and file type before uploading a file to a server? I've tried looking all over but never found anything to do something like this.

我建议如下:

$('input:file').change(
    function(e) {
        var files = e.originalEvent.target.files;
        for (var i=0, len=files.length; i<len; i++){
            console.log(files[i].fileName, files[i].type, files[i].fileSize);
        }
    });​

JS小提琴演示

由于JavaScript无法从选定的中删除​​文件fileList 对象,您必须对文件属性执行检查,并提示用户取消选择因文件类型或文件大小而被视为无效的文件(显然,阻止表单)提交):

As JavaScript can't remove files from the selected fileList object, you'd have to perform checks against the file attributes and prompt the user to deselect files that would be considered invalid due to file-type or file-size (and, obviously, prevent the form submitting):

$('input:file').change(
    function(e) {
        var files = e.originalEvent.target.files;
        for (var i=0, len=files.length; i<len; i++){
            var n = files[i].name,
                s = files[i].size,
                t = files[i].type;

            if (s > 100) {
                console.log('Please deselect this file: "' + n + '," it\'s larger than the maximum filesize allowed. Sorry!');
            }
        }
    });​

JS小提琴演示

(最后一个代码在Ubuntu 11.04上测试并使用Chromium 19和Firefox 15。)

(This last code tested and working in Chromium 19 and Firefox 15, both on Ubuntu 11.04.)