How to download image in angular 5 currently I am using saveAs function from
import { saveAs } from 'file-saver'
var blob = new Blob([this.attachment], { type: "image/png" });
console.log(blob);
console.log(window.btoa(blob.toString()));
if (this.attachment != null) {
saveAs(blob, 'attachment');
}
In this case image download but error in open.
convertBase64ToBlobData(base64Data: string, contentType: string='image/png', sliceSize=512) {
const byteCharacters = atob(base64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
First, you need to convert base64 to Blob data.
const blobData = this.convertBase64ToBlobData(base64content);
if (window.navigator && window.navigator.msSaveOrOpenBlob) { //IE
window.navigator.msSaveOrOpenBlob(blobData, filename);
} else { // chrome
const blob = new Blob([blobData], { type: contentType });
const url = window.URL.createObjectURL(blob);
// window.open(url);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With