This is an implementation using javascript, which takes to download an image from a URL using IE, Firefox and Chrome. It is necessary a small hack uses the httpclient to obtain the image as a Blob, then an element is created in the DOM and a click on that element is simulated to force the browser to download the image.
HTML:
<img src="IMAGE_URL" #img>
<a href="javascript:void(0);" (click)="downloadImage(img)">Download</a>
Typescript:
constructor(private httpClient: HttpClient) {
}
downloadImage(img) {
const imgUrl = img.src;
const imgName = imgUrl.substr(imgUrl.lastIndexOf('/') + 1);
this.httpClient.get(imgUrl, {responseType: 'blob' as 'json'})
.subscribe((res: any) => {
const file = new Blob([res], {type: res.type});
// IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(file);
return;
}
const blob = window.URL.createObjectURL(file);
const link = document.createElement('a');
link.href = blob;
link.download = imgName;
// Version link.click() to work at firefox
link.dispatchEvent(new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
}));
setTimeout(() => { // firefox
window.URL.revokeObjectURL(blob);
link.remove();
}, 100);
});
}