javascript 如何通过 FileReader 查看上传图片的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21672617/
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-10-27 21:27:02  来源:igfitidea点击:

How to check type of uploaded image through FileReader?

javascriptjquery

提问by malcoauri

There is the following code which makes preview before uploading on the server:

有以下代码可以在上传到服务器之前进行预览:

$(function(){
    var preview = $(".preview");

  $("#menu_image").change(function(event){
    var input = $(event.currentTarget);
    var file = input[0].files[0];
    var reader = new FileReader();
    reader.onload = function(e){
      var img = new Image;
      img.onload = function() {
        if ((img.with != 160) || (img.height != 160)) {
          return;
        }
        preview.attr("src", img.src);        
      };
      img.src = e.target.result;
    };

    reader.readAsDataURL(file);
  });
});

But this code doesn't check file's type. How can I do it? Thanks in advance.

但是此代码不检查文件的类型。我该怎么做?提前致谢。

回答by sailens

You don't need to load the FileReader to know file type. Using your code:

您无需加载 FileReader 即可了解文件类型。使用您的代码:

var file = input[0].files[0];

is as easy as checking the file.typeproperty.

就像检查file.type财产一样简单。

You can check if the file is an image:

您可以检查文件是否为图像:

if (file.type.match('image.*')) {
    console.log("is an image");
}

And which type of image is:

以及哪种类型的图像是:

if (file.type.match('image.*')) {
    console.log("is an image");
    console.log("Show type of image: ", file.type.split("/")[1]);
}    

Note that file.type.split("/")[1]should be an "image"

请注意,file.type.split("/")[1]应该是“图像”

回答by Manoj

You can do something similar to check the file extension:

您可以执行类似的操作来检查文件扩展名:

var extension = file.name.substring(file.name.lastIndexOf('.'));

    // Only process image files.
    var validFileType = ".jpg , .png , .bmp";
    if (validFileType.toLowerCase().indexOf(extension) < 0) {
        alert("please select valid file type. The supported file types are .jpg , .png , .bmp");
        return false;
    }

回答by Bhojendra Rauniyar

Try using the extension selector like this:

尝试使用这样的扩展选择器:

if($('img[src $= "jpg"]')) // if extension is jpg then dosomething
    dosomething;