JQuery Validate Image Upload File Type

折月煮酒 提交于 2019-12-08 09:00:05

问题


I have a JQuery script that validates the upload of avatar images but I need it to prevent the upload of anything other than PNG, JPG & GIF images. Any way of implementing this into the code I have? Here is the code:

$('#addButton').click(function () {
    var avatar = $("#avatarupload").val();
    if(avatar.length < 1) {
        avatarok = 0;
    }
    //ELSE IF FILE TYPE
    else {
        avatarok = 1;
    }
    if(avatarok == 1) {
        $('.formValidation').addClass("sending");
        $("#form").submit();
    }
    else {
        $('.formValidation').addClass("validationError");
    }
    return false;
});

回答1:


This should check the file extension

var extension = avatar.split('.').pop().toUpperCase();
if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
    avatarok = 0;
}

So the full code should looks like

$('#addButton').click(function () {
    var avatar = $("#avatarupload").val();
    var extension = avatar.split('.').pop().toUpperCase();
    if(avatar.length < 1) {
        avatarok = 0;
    }
    else if (extension!="PNG" && extension!="JPG" && extension!="GIF" && extension!="JPEG"){
        avatarok = 0;
        alert("invalid extension "+extension);
    }
    else {
        avatarok = 1;
    }
    if(avatarok == 1) {
        $('.formValidation').addClass("sending");
        $("#form").submit();
    }
    else {
        $('.formValidation').addClass("validationError");
    }
    return false;
});



回答2:


You can try for jquery validate for validation which is having accept :

vCategoryImage:{
   accept: "image/*"
}


来源:https://stackoverflow.com/questions/20950373/jquery-validate-image-upload-file-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!