1

I am trying to download a file with custom name from any url.

I am trying this on my code

downloadAttachment(attachment) {
    var a = document.createElement('a');
    a.href = attachment.url; //URL FOR DOWNLOADING
    a.download = 'CustomName.png';
    a.click();
}

and from view it is <button (click)="downloadAttachment(attachment)"></button>

It is downloading the file but filename is still picked up from the url.

How to add custom name to the file?

Anand Siddharth
  • 967
  • 1
  • 9
  • 30

3 Answers3

5

Download file with http.get:

    let queryApi = someApi
    this.http.get(queryApi, { responseType: 'blob', observe: 'response' })
        .subscribe(respone => {

            // file-type
            let fileName = 'custom-file-name.fileExt';             

            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(respone.body);
            link.download = fileName;
            link.click();
        });     
Yerkon
  • 4,548
  • 1
  • 18
  • 30
1

If the HTTP header Content-Disposition: is present and gives a different filename than this attribute, the HTTP header has priority over this attribute.

Check the response headers.

Chrome Download Attribute not working

So you will have to change your back end where the file is stored, if possible.

EDIT: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a

This attribute is only honored for links to resources with the same-origin.

Edit2:

getImage(imageUrl: string): Observable<File> {
    return this.http
        .get(imageUrl, { responseType: ResponseContentType.Blob })
        .map((res: Response) => res.blob());
}

Now you have a file in your memory, and you can save it however you will.

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47
0

Use in this way

<a [href]=URLoftheFile download="FilenameWithExtension">DownloadFile</a>

But does not work with cross origins

dasunse
  • 2,839
  • 1
  • 14
  • 32