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

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

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

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

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.

I also worked out a fiddle for 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; 

Try something like this:

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

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.
}

You don't need jquery here.

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)

using es6 includes method, makes it even more simple.

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