Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check type of uploaded image through FileReader?

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.

like image 203
malcoauri Avatar asked Feb 10 '14 08:02

malcoauri


2 Answers

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

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

is as easy as checking the file.type property.

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"

like image 186
sailens Avatar answered Oct 13 '22 00:10

sailens


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;
    }
like image 43
Manoj Avatar answered Oct 12 '22 22:10

Manoj