jQuery检查上传的文件是否为mp3

jQuery check that file upload is an mp3

本文关键字:是否 mp3 文件 检查 jQuery      更新时间:2023-09-26

使用正则表达式确保通过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 */
}

我认为IE是唯一一个添加类似"fakepath"前缀的浏览器,所以像这样的东西可能会更好:

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

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

这样,即使文件重命名为。Mp3也不会绕过控制。