jQuery how to check if uploaded file is an image without checking extensions?

前端 未结 7 1399
有刺的猬
有刺的猬 2021-01-31 09:17

Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a s

7条回答
  •  感动是毒
    2021-01-31 09:54

    If anyone comes here who is using jQuery Validator, a simple method would be:

    jQuery.validator.addMethod(
        "onlyimages",
        function (value, element) {
            if (this.optional(element) || !element.files || !element.files[0]) {
                return true;
            } else {
                var fileType = element.files[0].type;
                var isImage = /^(image)\//i.test(fileType);
                return isImage;
            }
        },
        'Sorry, we can only accept image files.'
    );
    

    which is then added to the .validate() function.

提交回复
热议问题