javascript - jQuery 在更改时验证文件类型

标签 javascript jquery

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

假设我有 2 个文件,即 a.jpg 和 b.pdf。现在,我将扩展名 b.pdf 更改为 b.jpg

a.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)。

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

关于javascript - jQuery 在更改时验证文件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28539746/

相关文章:

javascript - 我需要使用 jquery 让一个对象向左浮动,同时在 div 内淡出

javascript - Node JavaScript express JavaScript 格式数据从 sequelize 查询中获取

javascript - 防止错误 : getaddrinfo ENOTFOUND at GetAddrInfoReqWrap. onlookup 后应用程序崩溃

javascript - Flow - 可能类型与看似有效的默认对象参数不兼容

在用户首先单击页面之前,jquery keyup 不会被触发

javascript - 带有序列化和额外数据的 jQuery post()

javascript - 有没有办法限制 ng-repeat 中重复项目的数量?

c# - Visual Studio 打包 : Another version of this product is already installed

javascript - 如何使用 javascript 将 tr 移动到 tbody 中?

javascript - 子元素上的盒子阴影?