3

I have an URL in which the image that I need to download is. I want to make a button to download it. I tried this two options:

    const a = document.createElement('a');
        a.href = ImageURL;
        a.download = title;
        document.body.appendChild(a);
        a.click();

and

     window.location.href = t;

But both options just open a new window with the image.

Is there a way to instead of getting a new window the file just get downloaded?

raaaay
  • 496
  • 7
  • 14
Jorge Monroy
  • 408
  • 1
  • 5
  • 16

3 Answers3

1

This is not an angular issue. You can only use download attribute to force download of an image/file, if:

  • the server also says it should be downloaded, or
  • the image comes from the same domain.

It's an issue of cross-origin hrefs.

https://stackoverflow.com/a/17527821/4899523

https://stackoverflow.com/a/49736875/4899523

Abdul Rafay
  • 3,241
  • 4
  • 25
  • 50
1

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);
         });
     }
raaaay
  • 496
  • 7
  • 14
Pedro Bacchini
  • 876
  • 10
  • 13
0

You can try add download attribute in you HTML for example

<a href="IMAGE_URL" download="imagename.png">

But as I know there are some restrictions in new browsers.

Gh111
  • 1,362
  • 18
  • 19