jQuery - INPUT type = File,Image FileType验证选项?

AnA*_*ice 16 jquery jquery-plugins

我有以下内容:

<input id="user_profile_pic" name="user[profile_pic]" type="file">
Run Code Online (Sandbox Code Playgroud)

在服务器上,我检查以确保它是一个图像,但我想首先检查客户端.

如果选择的文件输入文件不是gif,jpg,png或bmp,我如何使用jQuery提醒用户?

谢谢

Jes*_*ord 28

您想要检查元素的值是什么,类似于:

$("#user_profile_pic").change(function() {

    var val = $(this).val();

    switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
        case 'gif': case 'jpg': case 'png':
            alert("an image");
            break;
        default:
            $(this).val('');
            // error message here
            alert("not an image");
            break;
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑

代码根据注释更改 - 现在删除所选文件的值(如果不是图像).


Har*_*gar 9

这很简单,不需要任何JavaScript验证.只需写这个,它只接受图像文件.

 <input type="file" multiple accept='image/*'> 
Run Code Online (Sandbox Code Playgroud)

  • 这很酷但它不能作为验证!它只是为了更容易处理从具有不同扩展名的文件夹中选择图像.你可以在这里看到 - > http://imageshack.us/a/img20/8451/switchzz.jpg (3认同)

Ale*_*lex 7

您可以使用正则表达式:

var val = $("#user_profile_pic").val();
if (!val.match(/(?:gif|jpg|png|bmp)$/)) {
    // inputted file path is not an image of one of the above types
    alert("inputted file path is not an image!");
}
Run Code Online (Sandbox Code Playgroud)

当然,您可以为正则表达式添加更多格式.有更复杂和全面的方法来实现这一点,但只要输入的图像文件路径以标准图像文件扩展名结束,此方法就可以完成任务.