Categories
JavaScript Answers

How to get Base64 encode file data from input form with JavaScript?

Spread the love

Sometimes, we want to get Base64 encode file data from input form with JavaScript.

In this article, we’ll look at how to get Base64 encode file data from input form with JavaScript.

How to get Base64 encode file data from input form with JavaScript?

To get Base64 encode file data from input form with JavaScript, we can call the FileReader object’s readAsBinaryString method.

For instance, we write

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

  reader.onload = () => {
    console.log(btoa(reader.result));
  };
  reader.onerror = () => {
    console.log("error");
  };

  reader.readAsBinaryString(file);
};

to set the input.onchange property to a function that runs when we change the selected file in the file input.

input is the file input.

In it, we get the first selected file with event.srcElement.files[0].

Then we create the reader FileReader object.

We then call reader.readAsBinaryString with the file to read it into a binary string/

We get the binary string in the reader.result property in the reader.onload method.

And we call btoa with the binary string to convert it to a base64 string.

Conclusion

To get Base64 encode file data from input form with JavaScript, we can call the FileReader object’s readAsBinaryString method.

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 *