Image preview before upload with javascript & jquery

This is very important when you upload a picture before you can examine it. That the picture is not right. In renowned social networking sites i.e. You may have watched the Image Preview on Facebook and Linkedin. For example, this option lets you see it when you pass another picture as your profile picture.

Step 1:- Add jQuery Library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Step 2:- Add Code File Upload
<table border="1" cellpadding="20">
<tr> <td><img id="preview" src="preview.jpg" width="350px" height="320px"/><br/></td></tr>
<tr><td><input type="file" id="imageFile"/></td></tr>
</table>
Step 3:- Add Code and Preview using JavaScript.

//Vlidaate only images file 

	$('#imageFile').change(function () {
        var imgPath = this.value;
        var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
        if (ext == "png" || ext == "jpeg" || ext == "gif" || ext == "jpg")
            readURL(this);
        else
            alert("Please select image file Only( png, jpeg,  jpg).")
    });

    //Once the file content is loaded, the image preview is attached to the HTML element.

    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.readAsDataURL(input.files[0]);
            reader.onload = function (e) {
                $('#preview').attr('src', e.target.result);
            };
           
        }
    }
Download Source Code Demo

Leave a Reply

Your email address will not be published. Required fields are marked *