Categories
JavaScript Answers

How to preview images before upload with JavaScript?

Spread the love

To preview images before upload with JavaScript, we use the FileReader constructor.

For instance, we write

<input type="file" />

to add the file input.

Then we write

const readURL = (file) => {
  return new Promise((res, rej) => {
    const reader = new FileReader();
    reader.onload = (e) => res(e.target.result);
    reader.onerror = (e) => rej(e);
    reader.readAsDataURL(file);
  });
};

const preview = async (event) => {
  const [file] = event.target.files;
  const url = await readURL(file);
  const img = document.querySelector("img");
  img.src = url;
};

const fileInput = document.querySelector("input");
fileInput.addEventListener("change", preview);

to call querySelector to get the file input.

And then we call addEventListener to listen for the change event with the preview listener function.

In preview we get the select file with event.target.files

Then we call the readURL function to read the file as a base64 URL.

We call readAsDataURL to get the base64 result.

We call res with e.target.result to return the base64 URL string with the promise.

In preview, we call querySelector to get the img element.

And we set the img.src attribute’s value to url to show the image we get with await.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.