file upload: check if valid image
Asked Answered
Y

5

14

I want to upload a file like this:

<input type="file" name="uploadPicture"/>

Is there any way to find out in javascript if the selected file is a valid image?

I know that I can check the file extension. The problem with that is someone can change a .txt file to .jpg and it would pass the validation.

Yezd answered 26/8, 2015 at 9:26 Comment(1)
How are you going to upload it? Maybe you can check it server side? Or you could load the image into the HTML File API and check the mime type.Gallantry
G
16

Firstly add accept="image/*" on your input, to accept only image files

<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>

Second, you can create image object to see if it is true image

function validateAndUpload(input){
    var URL = window.URL || window.webkitURL;
    var file = input.files[0];

    if (file) {
        var image = new Image();

        image.onload = function() {
            if (this.width) {
                 console.log('Image has width, I think it is real image');
                 //TODO: upload to backend
            }
        };

        image.src = URL.createObjectURL(file);
    }
};​
Grizzly answered 26/8, 2015 at 9:37 Comment(3)
What about non jQuery?Gallantry
this doesn't work. you also need to subscribe to the onerror event. onload will only be called if the image is valid.Yate
inventive answer!Balderas
S
28

Thank you, Arūnas Smaliukas. Your answer got me close to what I wanted.

Image.onload will only be called if the file is a valid image. So, it's not necessary to inspect this.width in the onload() call back.

To detect that it is an invalid image, you can use Image.onerror.

$().ready(function() {
  $('[type="file"]').change(function() {
    var fileInput = $(this);
    if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
      var url = window.URL || window.webkitURL;
      var image = new Image();
      image.onload = function() {
        alert('Valid Image');
      };
      image.onerror = function() {
        alert('Invalid image');
      };
      image.src = url.createObjectURL(fileInput[0].files[0]);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />
Sofar answered 3/12, 2015 at 18:5 Comment(3)
This is the best answerInelegancy
Remember to use URL.revokeObjectURL(image.src) to free up the memory used by this ObjectURL once it's no longer needed.Delly
is there anything in dropzone that does this? I'm using AWS to store files, so I have to override dropzone's icon-drawing to load an amazon-lambda-generated thumbnail image. But I would still like to verify the image works before uploading to S3, triggering lambda and waiting for the result.Shetler
G
16

Firstly add accept="image/*" on your input, to accept only image files

<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>

Second, you can create image object to see if it is true image

function validateAndUpload(input){
    var URL = window.URL || window.webkitURL;
    var file = input.files[0];

    if (file) {
        var image = new Image();

        image.onload = function() {
            if (this.width) {
                 console.log('Image has width, I think it is real image');
                 //TODO: upload to backend
            }
        };

        image.src = URL.createObjectURL(file);
    }
};​
Grizzly answered 26/8, 2015 at 9:37 Comment(3)
What about non jQuery?Gallantry
this doesn't work. you also need to subscribe to the onerror event. onload will only be called if the image is valid.Yate
inventive answer!Balderas
S
2

In order to check the image file type on client side, you can go for this:

function imageChange(e) {

    if (e.target.files[0].type.split("/")[0] === "image") {

      //code

    } else {

      //code

    }

}
Schinica answered 28/1, 2022 at 11:38 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Stereotropism
O
1

Except for adding accept="image/*" to the input check the file type property:

imageFile.type.includes('image');

or for very old browsers:

imageFile.type.match(/image/);

To get the file itself that imageFile is referencing add an event listener to the input. On change get the file with event.currentTarget.files[0];

Oeflein answered 12/5, 2021 at 12:11 Comment(0)
L
0

using a npm package could be an option, this looks promising: file type checker

Libertarian answered 4/6 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.