Javascript jQuery如何在不检查扩展名的情况下检查上传的文件是否是图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29805909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:02:27  来源:igfitidea点击:

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

javascriptjqueryvalidation

提问by Acallar

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 solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validatorbut to no avail... This is a snippet from my current code:

新手来了 问题是我目前已经编写了一个方法来检查上传的文件大小和扩展名以对其进行验证。但是,检查扩展不是解决方案,因为这种验证可能会导致很多问题。我想要做的是检查实际文件类型并在不使用扩展方法的情况下对其进行验证。我曾尝试使用jQuery 文件验证器,但无济于事......这是我当前代码的片段:

<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />

Script:

脚本:

App.Dispatcher.on("uploadpic", function() {         
        $(":file").change(function() {
            if (this.files && this.files[0] && this.files[0].name.match(/\.(jpg|jpeg|png|gif)$/) ) {
                if(this.files[0].size>1048576) {
                    alert('File size is larger than 1MB!');
                }
                else {
                    var reader = new FileReader();
                    reader.onload = imageIsLoaded;
                    reader.readAsDataURL(this.files[0]);
                }
            } else alert('This is not an image file!');
        });
        function imageIsLoaded(e) {
            result = e.target.result;
            $('#image').attr('src', result);
        };
    });

It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!

一旦上传输入更改并在验证后上传并显示图像,就会调用它。现在,我只关心验证,任何帮助或想法将不胜感激!

回答by Hoyen

Try something like this:

尝试这样的事情:

JavaScript

JavaScript

const file = this.files[0];
const  fileType = file['type'];
const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
if (!validImageTypes.includes(fileType)) {
    // invalid file type code goes here.
}

jQuery

jQuery

var file = this.files[0];
var fileType = file["type"];
var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
if ($.inArray(fileType, validImageTypes) < 0) {
     // invalid file type code goes here.
}

回答by Mike Antoniadis

You don't need jquery here.

你在这里不需要 jquery。

var mimeType=this.files[0]['type'];//mimeType=image/jpeg or application/pdf etc...


//ie image/jpeg will be ['image','jpeg'] and we keep the first value
    if(mimeType.split('/')[0] === 'image'){
       console.log('the file is image');
    }

You can also create a function to check when a file is image.

您还可以创建一个函数来检查文件何时是图像。

function isImage(file){
   return file['type'].split('/')[0]=='image');//returns true or false
}

 isImage(this.file[0]);

Update(es6)

更新(es6)

using es6 includesmethod, makes it even more simple.

使用es6includes方法,让它变得更加简单。

const isImage = (file) => file['type'].includes('image');

回答by rom5jp

Here is a quick tip if you just want to know if the file is a image:

如果您只想知道文件是否是图像,这里有一个快速提示:

var file = this.files[0];
var fileType = file["type"];

if (fileType.search('image') >= 0) {
  ...
}

回答by sujit

Pls refer a related query here. The answer here suggests to load the image in an Image object and check for it's width and height properties to be non zero. I think the technique can be used to solve your problem too.

在此处参考相关查询。此处的答案建议将图像加载到 Image 对象中,并检查其宽度和高度属性是否为非零。我认为该技术也可用于解决您的问题。

I also worked out a fiddlefor you to refer. Pertinent code below:

我还制作了一个小提琴供您参考。相关代码如下:

var img = new Image();
img.addEventListener("load",function(){
  alert('success');
});
img.addEventListener("error",function(){
      alert('error');
});
  img.src = picFile.result; 

回答by guest271314

What I want to do is to check the actual file type

我想要做的是检查实际的文件类型

Try accessing files[0].typeproperty . See Using files from web applications

尝试访问files[0].typeproperty 。请参阅使用来自 Web 应用程序的文件

$(":file").on("change", function(e) {

  console.log(this.files[0].type);
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />

回答by Neil Thompson

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

如果有人使用 jQuery Validator 来到这里,一个简单的方法是:

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.

然后将其添加到 .validate() 函数中。

回答by Oleg Sewruk

You could try to convert file type in string and after that slice this string like that:

您可以尝试在字符串中转换文件类型,然后像这样切片此字符串:

if(String(file.type).slice(0, 6) === 'image/') {....some code}