Categories
JavaScript Answers

How to load an image to a img element from a file input with JavaScript?

Spread the love

Sometimes, we want to load an image to a img element from a file input with JavaScript.

In this article, we’ll look at how to load an image to a img element from a file input with JavaScript.

How to load an image to a img element from a file input with JavaScript?

To load an image to a img element from a file input with JavaScript, we can use the FileReader constructor.

For instance, we write

<input type="file" />
<img id="myimage" height="200" />

to add the file input and the img element.

Then we write

const input = document.querySelector("input");

input.onchange = (event) => {
  const selectedFile = event.target.files[0];
  const reader = new FileReader();

  const imgtag = document.getElementById("myimage");
  imgtag.title = selectedFile.name;

  reader.onload = (event) => {
    imgtag.src = event.target.result;
  };

  reader.readAsDataURL(selectedFile);
};

to select the file input with querySelector.

And then we set its onchange property to a function that runs when we change file selection.

We get the first selected file with event.target.files[0].

Then we create a FileReader object and call readAsDataURL on it with the selectedFile as its argument.

When the file is read, read.onload runs.

In it, we set the imgtag.src property to event.target.result, which the base64 URL string with the image data.

We set imgtag to the img element that we selected with getElementById.

Conclusion

To load an image to a img element from a file input with JavaScript, we can use the FileReader constructor.

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 *