node.js - 下载 .exe 文件在 Angular 前端出现错误
问题描述
我在节点 JS 中使用它:-
let file = `${process.cwd()}/server/downloads/JRuler.exe`;
let filename = path.basename(file);
let stat = fs.statSync(file);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': stat.size,
'Content-disposition': 'attachment; filename=' + filename
});
let readStream = fs.createReadStream(file);
readStream.pipe(res);
这是在 Angular
download() {
this.clientAPI.get(Endpoints.DOWNLOAD).toPromise()
.then(res => {
console.log('res')
let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
console.log('blob',blob);
let a = document.createElement('a');
var ua=navigator.userAgent;
var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
if(msie){
navigator.msSaveOrOpenBlob(blob,res.filename);
}
else{
a.href = (URL.createObjectURL(blob));
a.download = res.filename;
document.body.appendChild(a);
a.click();
a.remove();
}
})
.catch(err => console.error("download error = ", err))
}
但我得到了错误: -
请建议我如何在角度前端处理。
解决方案
http 客户端需要 responseType blob 才能知道如何解析响应并在您的情况下返回订阅者或承诺。
download() {
this.clientAPI.get(Endpoints.DOWNLOAD, {responseType: 'blob'}).toPromise()
.then(res => {
console.log('res')
let blob = new Blob([new Uint8Array(res.file)],{type:'application/octet-stream'});
console.log('blob',blob);
let a = document.createElement('a');
var ua=navigator.userAgent;
var msie= ua.indexOf("MSIE") > -1 || ua.indexOf("Trident/") > -1;
if(msie){
navigator.msSaveOrOpenBlob(blob,res.filename);
}
else{
a.href = (URL.createObjectURL(blob));
a.download = res.filename;
document.body.appendChild(a);
a.click();
a.remove();
}
})
.catch(err => console.error("download error = ", err))
}
推荐阅读
- ipados - UIApplication.shared.requestSceneSessionRefresh 是如何工作的?
- javascript - 查找数组中的元素是否与另一个数组连续
- javascript - 反应:从调用状态的“blob”打开 PDF。使用“jsPDF”。返回:加载PDF文档失败
- sql-server - 存储过程读取带有命名空间的 xml 文件
- python - 我是否正确实施了 Prim 算法?- 迷宫生成
- android - 如何防止我的 Android 应用在后台停止?
- flutter - Flutter:必须向 Text 小部件提供非空字符串
- python - 如何在 Python 3.7 中同时运行 Plotly 和 Cufflinks?
- python - PyQt5有没有像Kivy一样的过渡效果
- kubernetes - 在 GKE 上使用 Dask Kubernetes 的工作器超时