Acallar Acallar - 2 years ago 104
Javascript Question

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

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 validator but to no avail... This is a snippet from my current code:

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


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;
} else alert('This is not an image file!');
function imageIsLoaded(e) {
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!

Answer Source

Try something like this:

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download