Typescript blob文件名没有链接

时间:2017-04-05 15:09:12

标签: google-chrome angular typescript blob

如何在打字稿中为blob设置文件名?对于IE,我可以轻松设置文件名,但对于Chrome,它看起来不可能。基本上我需要类似this solution但类似于

的东西
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);
    }
}

从html UI / angular 2:

调用此函数
<button type="button" class="btn btn-success"
(click)="downloadFile('test')">Download <br /> Download </button>

2 个答案:

答案 0 :(得分:18)

对于chrome(和firefox),你需要做一些工作来创建<a>元素并调用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);
}

答案 1 :(得分:0)

以下是适用于IE,Chrome和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();
    }
  }