Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Answer from Mohit Singh on Stack Overflow
Try this :-
<input id="inputFile" type="file" onchange="convertToBase64();" />
<script type="text/javascript">
function convertToBase64() {
//Read File
var selectedFile = document.getElementById("inputFile").files;
//Check File is not Empty
if (selectedFile.length > 0) {
// Select the very first file from list
var fileToLoad = selectedFile[0];
// FileReader function for read the file.
var fileReader = new FileReader();
var base64;
// Onload of file read the file content
fileReader.onload = function(fileLoadedEvent) {
base64 = fileLoadedEvent.target.result;
// Print data in console
console.log(base64);
};
// Convert data to base64
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
Here is how one person did it:
- http://blogs.adobe.com/formfeed/2009/08/base64_encode_a_pdf_attachment.html
Here is a link that suggests several other possible solutions:
- Base64 encoding and decoding in client-side Javascript
» npm install pdf-to-base64
You can just create an Image object and put the base64 as its src, including the data:image... part like this:
var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
It's what they call "Data URIs" and here's the compatibility table for inner peace.
Html
<img id="imgElem"></img>
Js
string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);
To receive the base64 value in the getPDF function you can use promises.
getPDF() {
let image = "assets/icon/logo.png";
this.getBase64Image(image).then(imageData => {
console.log("imageData", imageData);
}).catch(err => {
console.log(err);
});
}
getBase64Image(img) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", img, true);
xhr.responseType = "blob";
xhr.onload = function (e) {
console.log(this.response);
var reader = new FileReader();
reader.onload = function (event) {
resolve(event.target["result"]);
}
reader.onerror = function(e) {
reject(e);
};
var file = this.response;
reader.readAsDataURL(file)
};
xhr.onerror = function (e) {
reject(e);
}
xhr.send();
});
}
As suggested by @abadalyan, return a Promise from your getBase64Image.
Also do not forget to check the status of the response with readyState and status and handle any errors using XMLHttpRequest.onerror and XMLHttpRequest.ontimeout using the reject callback of the Promise.
You also have to check the FileReader errors with FileReader.onerror and FileReader.onabort, or you could use the FileReader.loadend callback instead of FileReader.load to make sure the promise always resolves even when you get a read error.
Here is an example with error handling:
function getBase64Image(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onerror = e => reject(new Error('Reading error.', e));
reader.onabort = e => reject(new Error('Reading abort.', e));
reader.onload = () => resolve(reader.result);
} else {
reject(request.statusText);
}
};
xhr.onerror = e => reject(new Error('Network error.', e));
xhr.ontimeout = e => reject(new Error('Timeout error.', e));
xhr.send();
});
}
getBase64Image('https://cors-anywhere.herokuapp.com/https://loremflickr.com/100/100').then(image => {
console.log(image);
document.querySelector('#img1').src = image;
}).catch(e => console.error(e.message || e));
getBase64Image('wrong-url').then(image => {
console.log(image);
document.querySelector('#img2').src = image;
}).catch(e => console.error(e.message || e));
<img id="img1" src="" alt="No image yet">
<img id="img2" src="" alt="No image yet">
Please use the below code to convert Base64 to PDF with the client side JavaScript. Pass the base64 data to the function base64ToArrayBuffer
function base64toPDF(data) {
var bufferArray = base64ToArrayBuffer(data);
var blobStore = new Blob([bufferArray], { type: "application/pdf" });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blobStore);
return;
}
var data = window.URL.createObjectURL(blobStore);
var link = document.createElement('a');
document.body.appendChild(link);
link.href = data;
link.download = "file.pdf";
link.click();
window.URL.revokeObjectURL(data);
link.remove();
}
function base64ToArrayBuffer(data) {
var bString = window.atob(data);
var bLength = bString.length;
var bytes = new Uint8Array(bLength);
for (var i = 0; i < bLength; i++) {
var ascii = bString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
};
You need some kind of JavaScript PDF library to do this.
jsPDF for instance has a addImage() method (https://rawgit.com/MrRio/jsPDF/master/docs/module-addImage.html) which accepts a base64 string as input