在我的services.service.ts文件中,我传递了一个zip名称并调用了路由
services.service.ts
downloadFile(name) {
console.log(name);
let newName = name+".zip";
console.log(newName);
return this.http
.get(`/services/downloadFile/${name}`, {
responseType: ResponseContentType.Blob })
.pipe(map(res => {
return {
filename: newName,
data: res.blob()
};
}))
.subscribe(res => {
// console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
从service.js调用此路由后,zip文件被下载到Windows,但没有数据 service.js
router.get('/downloadFile/:name', function (req, res) {
let name = req.params.name;
let newName = name+".zip";
res.download(`./config/${newName}`, newName, function (err) {
if (err) {
console.log(err);
console.log("ERROR APPEARED");
} else {
console.log('file uploaded :)');
}
});
});
此代码执行没有错误(我将在控制台中获得“文件已上传:)”),但是下载的zip文件由于其中不包含数据(适当的数据)而无法打开或提取
答案 0 :(得分:2)
我曾经遇到过类似的问题-如果您使用基于令牌的身份验证,则可能忘记了将其添加到标题中,请尝试:
.get(`/services/downloadFile/${name}`, {headers: new Headers({
'Content-Type': 'application/json', // INFO: Format set to JSON
'authorization': yourAuth.token.etc // INFO: Attach token
}),responseType: ResponseContentType.Blob })
希望能帮助您解决问题。.