Reputation: 4209
In my angular 4 application I have a gallery with some thumbnails, every thumbnails have a download button.
I want to start the download of the image when this button is clicked, is it possible in angular?
Now when I click in the button I have:
component.ts
downloadImage(downloadLink) {
this.mediaService.getImage(downloadLink).subscribe(
(res) => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL);
}
);
}
And in the service:
getImage(imageUrl: string) {
return this.http.get(imageUrl, {observe: 'response', responseType: 'blob'})
.map((res) => {
return new Blob([res.body], {type: res.headers.get('Content-Type')});
})
}
But obviously window.open(fileURL)
opens a new window with the image.
Upvotes: 0
Views: 13392
Reputation: 4209
Finally I use this method:
this.mediaService.getImage(downloadLink).subscribe(
(res) => {
const a = document.createElement('a');
a.href = URL.createObjectURL(res);
a.download = title;
document.body.appendChild(a);
a.click();
});
}
Upvotes: 1
Reputation: 4207
To direcly download the image you can try with :
downloadImage(downloadLink) {
this.mediaService.getImage(downloadLink).subscribe(
(res) => {
const fileURL = URL.createObjectURL(res);
window.location.href = fileUrl;
}
);
}
Upvotes: 1