jquery在提交之前验证文件类型和文件大小 [英] jquery to verify file type and file size before submitting

查看:67
本文介绍了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.)

这篇关于jquery在提交之前验证文件类型和文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆