在我的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无法打开或解压缩,因为它将不包含数据(适当的数据)。
发布于 2018-11-16 12:14:53
我曾经遇到过类似的问题--如果您使用基于令牌的auth,您可能忘记在标题中添加这些内容,请尝试:
.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 })希望能帮助你解决你的问题。
https://stackoverflow.com/questions/53334663
复制相似问题