0

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.

Alessandro Celeghin
  • 4,039
  • 14
  • 49
  • 95

2 Answers2

1

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;
  }
);
}
Boulboulouboule
  • 4,087
  • 1
  • 13
  • 29
1

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();
  });
}
Alessandro Celeghin
  • 4,039
  • 14
  • 49
  • 95
  • if i pass directly image url on that i got error:Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided – Kapil Soni Sep 24 '20 at 08:52