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

Spread the love

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

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

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

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

For instance, we write

<input type="file" onchange="onFileSelected(event)" />
<img id="myimage" height="200" />

to add the input and img elements.

Then we write

function onFileSelected(event) {
  const [selectedFile] = event.target.files;
  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 set the onchange attribute to onFileSelected(event) to use the onFileSelected function as the input’s change event listener.

In it, we get the file from event.target.files.

Then create a FileReader object.

Next, we select the img element with getElementById.

Then we set the reader.onload property to a function that runs when readAsDataURL is done.

In it, we get the read image base64 URL string from event.target.result and set the img element’s src attribute to the base64 URL string.

Finally, we call readAsDataURL to read the file into a base64 URL.

Conclusion

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

Leave a Reply

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