Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file upload: check if valid image

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.

like image 711
Moraru Alex Avatar asked Aug 26 '15 09:08

Moraru Alex


People also ask

How do I know if my image is uploaded or not?

Just check if it starts with image/ . String fileName = uploadedFile. getFileName(); String mimeType = getServletContext(). getMimeType(fileName); if (mimeType.

How can I tell what file type an image is?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.


2 Answers

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" />
like image 194
Kirby Avatar answered Sep 21 '22 03:09

Kirby


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);
    }
};​
like image 22
Arūnas Smaliukas Avatar answered Sep 23 '22 03:09

Arūnas Smaliukas