jQuery更改时验证文件类型

jQuery Validate File Type On Change

本文关键字:文件 类型 验证 jQuery      更新时间:2023-12-16

我有一个jQuery文件上传。该上传功能仅允许图像类型。.jpg, .gif, .png

假设我有两个文件,那就是.jpg&b.pdf。现在,我将b.pdf的扩展名更改为b.jpg

.jpg是原始图像
b.jpg不是原始图像。

我的问题是,如何验证b.jpg不是原始图像?

这是我的JS脚本:

$(function()
{
    $("#file").change(function()
    {
        var file = this.files[0];
        var imagefile = file.type;
        var match= ["image/jpeg","image/png","image/jpg"];
        var file_size = this.files[0].size;
        if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
        {
            alert("Invalid File");
        }
        else
        {
            var reader = new FileReader();  
            reader.onload = imageIsLoadeds;
            reader.readAsDataURL(this.files[0]);
        }
        function imageIsLoadeds(e)
        {
            if(file_size>=1024000)
            {
                alert("File Size Error");
            }
            else
            {
                $('#image').attr('src', e.target.result);
            }
        }
    }
}

您必须验证上传内容的MIME类型。

首先选择所需的MIME类型(参考:http://www.freeformatter.com/mime-types-list.html)。

其次,您可以使用jQueryValidationPlugin来验证上传内容的MIME类型。(参考:http://jqueryvalidation.org/accept-method/)