Sometimes, we want to convert binary data to base64 with JavaScript.
In this article, we’ll look at how to convert binary data to base64 with JavaScript.
How to convert binary data to base64 with JavaScript?
To convert binary data to base64 with JavaScript, we can use a FileReader instance.
For instance, we write:
<input type="file" />
to add a file input.
Then we write:
const input = document.querySelector('input')
const reader = new FileReader()
reader.onload = (e) => {
  console.log(e.target.result);
}
input.onchange = (e) => {
  const [file] = e.target.files
  reader.readAsDataURL(new Blob([file]));
}
to select the input with document.querySelector.
Then we create the FileReader instance and set its onload property to a function that has the file reader result.
Then we set the input.onchange property to a function that gets the file from the input.
And then we call reader.readAsDataURL with a Blob instance containing the file.
Conclusion
To convert binary data to base64 with JavaScript, we can use a FileReader instance.
 
		
One reply on “How to convert binary data to base64 with JavaScript?”
Hi!
How can you do the inverse process? from base64 to a binary file?
Good Article!