JavaScript

Preview an image loaded in an input file with JavaScript

February 16, 2022

Preview an image loaded in an input file with JavaScript

In this article we will learn how to preview an image loaded in an input file, that is, after inserting the image in a form we will display it on the page.

preview an image loaded in an input file cover

What’s up programmer, ok? Let’s learn something new!

Whenever we insert an image into a form, only its name and extension are displayed.

What can generate doubt in the user, if he inserted the correct image

So the idea of making a preview is excellent, we can insert a preview before sending it to the server

So let’s go to the code:

<form>
 <div>
  <input id="img-input" type="file" name="image">
 </div>
 <div id="img-container">
  <img id="preview" src="">
 </div>
 <div>
  <input type="submit" value="Send">
 </div>
</form>

This will be our base HTML, with the form and input files

In addition, we create a div with the id of img-container, which contains an image without src

With JavaScript we will fill this src, with the image sent, thus making the preview

See the JS code:

function readImage() {
 if (this.files && this.files[0]) {
  var file = new FileReader();
  
  file.onload = function(e) {
   document.getElementById("preview").src = e.target.result;
  };
 
  file.readAsDataURL(this.files[0]);
 }
}

document.getElementById("img-input").addEventListener("change", readImage, false);

What happens here is:  we have a change event mapping, in the input of files

When a change occurs (send image), the readImage function is triggered

This function has as main objective to read the uploaded file and change the preview attribute to the src of the image

Making the image appear in the div below the input

And so we can show the preview of the image loaded in input file

Example of the achieved result:

Conclusion

In this article we learned  how to display the preview of the image added to the form

We use JavaScript to manipulate the src of an image previously inserted in the HTML code

So that when the file is uploaded, it displays the image we uploaded

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x