Categories
JavaScript Answers

How to preview an image before and after upload with JavaScript?

Spread the love

Sometimes, we want to preview an image before and after upload with JavaScript.

In this article, we’ll look at how to preview an image before and after upload with JavaScript.

How to preview an image before and after upload with JavaScript?

To preview an image before and after upload with JavaScript, we can read the image file into a URL that we set as the value of the img element’s src attribute with a FileReader instance.

For instance, we write:

<form>
  <input type="file" />
  <img src="">
</form>

to add a form with an input and an img element.

Then we write:

const input = document.querySelector('input')
const img = document.querySelector('img')
const reader = new FileReader();

reader.onload = (e) => {
  img.src = e.target.result;
}

input.onchange = (e) => {
  const [file] = e.target.files
  reader.readAsDataURL(file);
}

We call document.querySelector to select the input and img elements.

Next, we create a new FileReader instance.

And then we set the reader.onload property to a function that gets the image URL from e.target.result and set that as the value of the img.src property.

Next, we set the input.onchange property to a function that gets the selected file from e.target.files.

And then we call reader.readAsDataUrl with file to read the file into a URL string.

Conclusion

To preview an image before and after upload with JavaScript, we can read the image file into a URL that we set as the value of the img element’s src attribute with a FileReader instance.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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