I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
I found this solution from the sourcecode of how Chrome takes full-page screenshots.
const base64string = "";
const pageImage = new Image();
pageImage.src = 'data:image/png;base64,' + base64string;
pageImage.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = pageImage.naturalWidth;
canvas.height= pageImage.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImage(pageImage, 0, 0);
console.log(canvas, pageImage)
saveScreenshot(canvas);
}
function saveScreenshot(canvas) {
let fileName = "image"
const link = document.createElement('a');
link.download = fileName + '.png';
console.log(canvas)
canvas.toBlob(function(blob) {
console.log(blob)
link.href = URL.createObjectURL(blob);
link.click();
});
};
Simple way to do this with Javascript...
var a = document.createElement("a"); //Create <a>
a.href = "data:image/png;base64," + ImageBase64; //Image Base64 Goes here
a.download = "Image.png"; //File name Here
a.click(); //Downloaded file
If you already have it in base64, add the image tag in front of the base64. attach it to the element
png64 = "data:image/" + png64;
$('#downloadPNG').attr('href', png64);
Add the file name that you want when downloading to the download
tag.
<a download="chart.png" id="downloadPNG">Export img</a>
It is so simple just use function below:
// Parameters:
// contentType: The content type of your file.
// its like application/pdf or application/msword or image/jpeg or
// image/png and so on
// base64Data: Its your actual base64 data
// fileName: Its the file name of the file which will be downloaded.
function downloadBase64File(contentType, base64Data, fileName) {
const linkSource = `data:${contentType};base64,${base64Data}`;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}