How to Show an image preview before upload in jquery

In this tutorial we’ll learn How to Show an image preview before upload in jquery, Showing image before upload is quite easy after HTML release File API , which allows you to create applications that let the user interact with files locally, That means you can upload file and read file data locally and render in browser. It is good idea to display image preview before upload , It feels users that he/she is going to upload right file.



Below is a quick example of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL.
show-img-preview

HTML

<form id="form">
    <input type='file' id="file" />
    <br/>
   <span style="color:red"> Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)</span><br/>
    <img id="img" src="http://placehold.it/200x200" alt="No image uploaded" />
</form>



JavaScript + Jquery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function() {
 
$("#file").change(function () {
        readImgPath(this);
    });
 

function readImgPath(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
 
            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }
 
            reader.readAsDataURL(input.files[0]);
        }
    }
 
})
</script>

Above function readImgPath will read image as DataURL and render image source to display thumbnail.

See live demo and download source code.

DEMO

DOWNLOAD

If you like this post please don’t forget to subscribe my public notebook for more useful stuff