Convert a File to base64 String in JavaScript

The idea behind my concept is simple. Firstly pick the file which you want to convert from the system’s HDD using HTML5 file browser. Once the file is selected, read the file as binary string using the FileReader API. At last convert the binary string to base64 using JavaScript.

Let’s See in detail:-

Attach a file browser to your html using the HTML5 input tag as type file.

Once a file is selected by clicking on the Browse button, the onchange event is triggered and the function attached to it is called by sending the file browser as object which intern contains the details of the selected file.

Now to read the selected file, we need to create a FileReader object by calling the constructor of FileReader API.

After the object is created, read the file as binary string using the readAsBinaryString() of the FileReader API method by passing the selected file object as parameter.

FileReader API will call the onload method once the file is completely read and the binary string will be set as the reader object’s result key.

Let us do the conversion from binary to base64 inside the onload function using the JavaScript btoa() method.

The function goes like this:-

check the demo to convert a file to base64 :- base64 converter demo

watch a small video on the article :- Youtube link

Convert base64 to file

Happy Coding………………:)

Tagged as: