js File to base64 code example

Example 1: javascript base64 encode

var string = "Hello folks how are you doing today?";
var encodedString = btoa(string); // Base64 encode the String
var decodedString = atob(encodedString); // Base64 decode the String

Example 2: convert file into base64 in javascript

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
  data => console.log(data)
);

Example 3: javascript base64 encode file input

var fileInput = document.getElementById('#myInputID');

var reader = new FileReader();
reader.readAsDataURL(fileInput.files[0]);

reader.onload = function () {
	console.log(reader.result);//base64encoded string
};
reader.onerror = function (error) {
	console.log('Error: ', error);
};

Example 4: Converting file to base64 on Javascript client side

// Convert file to base64 string
export const fileToBase64 = (filename, filepath) => { 
return new Promise(resolve => {    
var file = new File([filename], filepath);    
  var reader = new FileReader();    // Read file content on file loaded event
  reader.onload = function(event) { 
    resolve(event.target.result);    };        // Convert data to base64
  reader.readAsDataURL(file);  
});
};
// Example call:
fileToBase64("test.pdf", "../files/test.pdf").then(result => {  console.log(result);});