convert pdf file to base64 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: convert pdf to base64 javascript
if (window.File && window.FileReader && window.FileList && window.Blob) {
document.getElementById('files').addEventListener('change', handleFileSelect, false);
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var binaryData = e.target.result;
var base64String = window.btoa(binaryData);
document.getElementById('base64').value = base64String;
alert('File converted to base64 successfuly!\nCheck in Textarea');
};
})(f);
reader.readAsBinaryString(f);
}