I have a base64-encoded image from the server for which I want to force the download through JavaScript. Is is possible?
In my Angular App, I am getting the base 64 files from server.
In Html:-
<button type="button" (click)="downloadFile(fileName,base64data,fileType)"></button>
In Ts:-
downloadFile(fileName:string,data: any,fileFormat:string): void {
const linkSource = 'data:'+fileFormat+';base64'+data;
const downloadLink = document.createElement("a");
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
You can try this :
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Download Text File DataURL Demo</title>
<style>
body{ font: menu; }
</style>
<script src='//js.zapjs.com/js/download.js'></script>
</head>
<body>
<h1>Download Text File DataURL Demo</h1>
<main></main>
<script>
download("data:application/octet-stream;base64,YOUR BASE64URL", "dlDataUrlText.jpeg", "application/octet-stream;base64");
</script>
</body>
</html>
download tag downloads the image using the script included.
For reference you can try this URL : http://danml.com/download.html
At first: This question is extremly browser dependent! I tried many, so I came up to answer this question that way:
You should put the base64-Data inside the src-Tag of an IMG-Element: How to display Base64 images in HTML? Then you can right click the Image and click "Save Image..." (or similar) in these browsers:
Also on Android with Chrome and Firefox. Biggest file working was 23 MB PNG-File in IE 11 and Safari 13. But Firefox and Chrome did also work for 86 MB JPEG.
If you want to download it using JavaScript (without any back-end) use:
window.location.href = 'data:application/octet-stream;base64,' + img;
where img
is your base64 encoded image.
If you want to allow the user to specify a file name, use the download
attribute of the a
tag:
<a download="FILENAME.EXT" href="data:image/png;base64,asdasd...">Download</a>
In my React App, I was getting the base 64 images from an API, I stored it in a global prop and downloaded it with the help of <a>
tag.
<a href={`data:application/octet-stream;base64,${this.props.base64image}`} download={"imageName"}>Click to Download the image</a>
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