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

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