Search code examples
javascripthtmlfile-upload

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.


Solution

  • 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);
        }
    };​