Typescript blob filename without link
Asked Answered
S

2

12

How to set file name for blob in typescript? For IE, I can setup file name easily but for Chrome it looks impossible. Basically I need something similar to this solution but with typescript

downloadFile(data: any) {
    var blob = new Blob([data], {type: 'text/csv'});
    let fileName = 'my-test.csv';

    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        //save file for IE
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {
        //save for other browsers: Chrome, Firefox

        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }
}

this function is called from html UI/angular 2:

<button type="button" class="btn btn-success"
(click)="downloadFile('test')">Download <br /> Download </button>
Statutory answered 5/4, 2017 at 15:9 Comment(2)
have you tried to add a download attribute to your button?Electrolyte
it won't work wit hdownload attributeStatutory
W
30

For chrome (and firefox) you need to do a little work around with creating an <a> element and calling click:

downloadFile(data: any): void {
    const blob: Blob = new Blob([data], {type: 'text/csv'});
    const fileName: string = 'my-test.csv';
    const objectUrl: string = URL.createObjectURL(blob);
    const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;

    a.href = objectUrl;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();        

    document.body.removeChild(a);
    URL.revokeObjectURL(objectUrl);
}
Waly answered 5/4, 2017 at 15:13 Comment(3)
Good answer, just one problem at the last line. I think it should be objectUrl instead of urlSilvasilvain
You might want to add a small Timeout function for the removeChild otherwise certain browsers like Edge will remove the anchor before completing the clickNorry
After more than a day's worth of struggle, this finally helped. Thanks!Ssm
K
1

Here is the download method working on IE, chrome and firefox:

  downloadCsvFile(data, fileName) {
    const csvName = fileName +  '.csv';
    const blob = new Blob([data], {type: 'text/csv'});
    if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE
      window.navigator.msSaveOrOpenBlob(blob, csvName);
      window.navigator.msSaveOrOpenBlob(blob, csvName);
    } else { //Chrome & Firefox
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = csvName;
      a.click();
      window.URL.revokeObjectURL(url);
      a.remove();
    }
  }
Knotweed answered 11/7, 2019 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.