google-chrome - 没有链接的 Typescript blob 文件名

标签 google-chrome angular typescript blob

如何在 typescript 中为 blob 设置文件名?对于 IE,我可以很容易地设置文件名,但对于 Chrome,它看起来是不可能的。基本上我需要类似于 this solution 的东西但是用 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);
    }
}

此函数从 html UI/angular 2 调用:

<button type="button" class="btn btn-success"
(click)="downloadFile('test')">Download <br /> Download </button>

最佳答案

对于 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);
}

关于google-chrome - 没有链接的 Typescript blob 文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235129/

相关文章:

javascript - 如何从 Chrome 扩展中的 WebView 访问 cookie

javascript - Chrome 只是没有完成加载 JS 文件

angular - FontAwesome 无法使用跨度与 Angular 一起使用

html - 复选框需要单击两次才能取消选中吗?

reactjs - 使用 Typescript(TSX 文件)将 Prop 传递给 React 中的子组件

google-chrome - 为什么 Chrome 浏览器频繁更改端点

javascript - 网站停止使用 Chrome 版本 32

javascript - Angular 2 : [hidden] and *NgIf not working?

javascript - 如何删除值并向 JavaScript 对象添加索引列?

typescript - rxjs : Observable. of(...).delay 不是函数