Preview image before uploading in jQuery

I hope you are familiar with the HTML file input field. From the file input field, users can choose any file that needs to be uploaded.

Did you ever think of how it was if the user can see the preview image before upload?

I think, you have already seen on many websites, where you select an image and see the image on the webpage instantly. This is to make you confirm which picture you are going to upload.

So here in this post, I am going to show you how to preview image before uploading in jQuery from HTML file input.


Also, read:


Before we are going to do it, let’s first create our HTML input field and the container where our preview image will be displayed:

 <input type="file" id="image_field" class="form-control">
 <div id="preview_image"></div>

In the above HTML code, we have a file input type with ID “image_field” and a div element with ID “preview_image” which will contain the preview image that we can see before upload.

Now let’s see our JavaScript code. Before we write our JavaScript code we must have to load the jQuery on the page.

Now see the jQuery code below to show the image before upload:


   $(document).on("change","#image_field", function(){

      var oFReader = new FileReader();

      oFReader.onload = function (oFREvent) {
          $('#preview_image').html('<img src="''">');



In the above code, we have used the jQuery change() method. Inside this method, we have written our code that we have to run to display the image before user upload from the HTML input field.

Inside the change() method, we have used the JavaScript FileReader object. It will read our image file after we select an image using the file type input.

Next, we have used the JavaScript load event handler upon the file input. Inside the load event, we have the code to show the data as HTML in our div element that has the ID “preview_image”. Here we are going to see our preview image soon.

Now it’s time to test our code on the browser. If we run the code on our browser, choose and select an image using the file input type,¬† we will able the see the image preview on the web page.

So we have successfully able to preview or show the image on the web page before the upload process.

Is that not amazing? What you think about what we have done?


Leave a Reply

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