Convert File To Base64 String Javascript Code Example


Example 1: 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 2: 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);
};

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable