对不起,如果有另一篇文章谈论这个,但我找不到它,这让我发疯。
我做了一个web服务,以字节数组的形式返回一个文件,它工作正常。之后,
另一方面,我正在开发一个名为de webservice的Angular 4站点,并尝试下载获取的文件。所以我想出了以下代码:
downloadFile() {
let theFile;
this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
.subscribe(data => {
theFile = new Blob([data], { type: 'application/octet-stream' });
let url = window.URL.createObjectURL(theFile);
console.log(url);
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
console.log(link);
link.click();
},
error => {
console.log(error);
},
() => console.log('File download completed.'));
}
此代码使用Chrome正常工作,但Internet Explorer不会将文件下载到浏览器。
感谢console.log()
我可以看到创建的链接元素是不同的:
有人能帮助我吗?非常感谢提前!!
我必须为我的应用程序实现相同的功能,我使用了这个库:File-Saver
它安静得心应手。
最后,我发现了这个类似的post。我修改了我的功能,现在看起来像这样(它现在在Chrome和IE11中完美运行):
downloadFile() {
let theFile;
this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
.subscribe(data => {
theFile = new Blob([data], { type: 'application/octet-stream' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(theFile, 'file.pdf');
} else {
const url = window.URL.createObjectURL(theFile);
window.open(url);
const link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.click();
}
},
error => {
console.log(error);
},
() => console.log('File download completed.'));
}
谢谢!