没有链接的Typescript Blob文件名 [英] Typescript blob filename without link

查看:387
本文介绍了没有链接的Typescript Blob文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在打字稿中为Blob设置文件名?对于IE,我可以轻松设置文件名,但对于Chrome,它似乎是不可能的.基本上,我需要类似于此解决方案的东西,但带有打字稿

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

此函数从html UI/角度2调用:

this function is called from html UI/angular 2:

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

推荐答案

对于chrome(和Firefox),您需要做一些工作来创建<a>元素并调用click:

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

这篇关于没有链接的Typescript Blob文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆