Preview an image before uploding using javascript

While creating html forms, most of us include an input field for uploading files.

If the type of file to be uploaded is image, it would be great to allow the site user to preview the image before actual upload.

This can be achieved by using javascript’s File reader.

 

Html markup

<img id="uploadedImg" alt="Image Preview"/>
<input type="file" id="imgInput">

And the corresponding javascript

$('#imgInput').change(function(){
    var file = document.querySelector('input[type=file]').files[0];
    var reader = new FileReader(); 
    reader.onloadend = function () 
    { 
        $('#uploadedImg').attr('src', reader.result); } 
        if (file){ 
            reader.readAsDataURL(file); 
        } else { 
            preview.src = ""; 
        } 
});