Google chrome 不带链接的Typescript blob文件名
如何在typescript中设置blob的文件名?对于IE,我可以轻松设置文件名,但对于Chrome来说,这似乎是不可能的。基本上我需要类似的东西,但与打字脚本Google chrome 不带链接的Typescript blob文件名,google-chrome,angular,typescript,blob,Google Chrome,Angular,Typescript,Blob,如何在typescript中设置blob的文件名?对于IE,我可以轻松设置文件名,但对于Chrome来说,这似乎是不可能的。基本上我需要类似的东西,但与打字脚本 downloadFile(data: any) { var blob = new Blob([data], {type: 'text/csv'}); let fileName = 'my-test.csv'; if (window.navigator && window.navigator.ms
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调用此函数:
<button type="button" class="btn btn-success"
(click)="downloadFile('test')">Download <br /> Download </button>
下载
下载
对于chrome(和firefox),您需要创建一个
元素并调用单击:
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);
}
以下是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();
}
}
您是否尝试将下载
属性添加到您的按钮
?它与hdownload attributeGood answer无效,最后一行只有一个问题。我认为应该是objectUrl
而不是url
。您可能需要为removeChild添加一个小的超时功能,否则某些浏览器(如Edge)会在经过一天多的努力后,在完成单击之前移除锚,这最终起到了帮助。谢谢