jQuery检查文件上传是否为mp3

时间:2013-03-29 23:04:17

标签: javascript regex file upload submit

使用正则表达式确保通过input[type="file"]上传的文件是MP3。事情出错了,我正在测试的文件没有通过。

感谢您的帮助!

HTML

<input type="file"/>

的JavaScript

var file = $input.find('input[type="file"]'),
    val  = file.val(),
    type = /^([a-zA-Z0-9_-]+)(\.mp3)$/;

submit.attr('disabled', 'disabled').addClass('deac');

if (!val){

    modal("The upload can't be empty.", true);
} else if (!type.test(val)){

    modal("The song must be in MP3 format.", true);

    /***********
     *
     * Getting caught here- even with a valid .mp3 file that _should_ pass the regex
     * in my test case using mamp as a localhost, val = C:\fakepath\1.mp3 
     *
     ***********/
} else {

    /* Success */
}

2 个答案:

答案 0 :(得分:1)

我认为最好的解决方案是使用方法mime()

这样,即使用a重命名文件也是如此。 Mp3未被规避控制。

答案 1 :(得分:0)

我认为IE是唯一一个添加“fakepath”前缀之类的浏览器,所以这样的东西可能效果更好:

type = /^(?:[A-Z]:\\fakepath\\)?([a-zA-Z0-9_-]+)(\.[Mm][Pp]3)$/;
相关问题