Categories
JavaScript Answers

How to make a simple image upload using JavaScript and HTML?

Spread the love

Sometimes, we want to make a simple image upload using JavaScript and HTML.

In this article, we’ll look at how to make a simple image upload using JavaScript and HTML.

How to make a simple image upload using JavaScript and HTML?

To make a simple image upload using JavaScript and HTML, we can add a file input and img element.

And then we can get the selected file from the file input and show it in the img element.

For instance, we write

<input type="file" /> <br /><img id="myImg" src="#" />

to add the file input and img element.

Then we write

document.querySelector('input[type="file"]').addEventListener("change", (e) => {
  if (e.target?.files?.[0]) {
    const img = document.querySelector("img");
    img.onload = () => {
      URL.revokeObjectURL(img.src);
    };

    img.src = URL.createObjectURL(e.target?.files[0]);
  }
});

to select the file input with querySelector.

And then then we listen for its change event with addEventListener.

In the event listener, we get the file from e.target?.files?.[0].

Then we get the img element with querySelector.

We set the src property of the img element to the URL base64 string that we get by calling createObjectURL with the file object.

Then when the image is loaded, we call revokeObjectURL to clear the resources for creating the URL.

Conclusion

To make a simple image upload using JavaScript and HTML, we can add a file input and img element.

And then we can get the selected file from the file input and show it in the img element.

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 *