Categories
JavaScript Answers

How to get the image before submitting the form with HTML input type=file and JavaScript?

Spread the love

Sometimes, we want to get the image before submitting the form with HTML input type=file and JavaScript.

In this article, we’ll look at how to get the image before submitting the form with HTML input type=file and JavaScript.

How to get the image before submitting the form with HTML input type=file and JavaScript?

To get the image before submitting the form with HTML input type=file and JavaScript, we use the files property.

For instance, we write

<input type="file" onchange="previewFile()" /><br />
<img src="" height="200" alt="Image preview..." />

to add a file input and an img element.

Then we write

const previewFile = () => {
  const preview = document.querySelector("img");
  const file = document.querySelector("input[type=file]").files[0];
  const reader = new FileReader();

  reader.onloadend = () => {
    preview.src = reader.result;
  };

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
};

to select the img element and file input with querySelector.

We get the select file with document.querySelector("input[type=file]").files[0].

And we read the file into a base64 URL with readAsDataURL.

reader.result has the file as a base64 URL string.

Conclusion

To get the image before submitting the form with HTML input type=file and JavaScript, we use the files property.

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 *