Anand Siddharth
Anand Siddharth

Reputation: 977

Custom file name of file to download in Angular 2

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?

Upvotes: 1

Views: 7219

Answers (3)

dasunse
dasunse

Reputation: 3099

Use in this way

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

But does not work with cross origins

Upvotes: 0

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10157

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.

Upvotes: 1

Yerkon
Yerkon

Reputation: 4798

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();
        });     

Upvotes: 6

Related Questions