目前我的 nodejs 服务正在这样做:
...
fs.writeFileSync('filelocation/data.xlsx', theData, 'binary');
reponse.sendFile('filelocation/data.xlsx');
reponse.download('filelocation/data.xlsx'); // I tried this one also
...
但现在如何使用 HttpClient
从 Angular 前端下载它?这不起作用:
this.httpclient.get(url).subscribe(response => {
console.log(response); // Or whatever I need to do to download the file
});
我希望调用调出文件资源管理器以便我可以保存文件。我如何让这个工作?如果您需要我提供更多信息,请告诉我。
最佳答案
创建一个 component.ts 并将文件名传递给 fileService。 在 fileService 内部创建下载功能并使用该功能将文件名传递给后端服务器。可以使用“另存为”下载文件。安装文件保护程序(npm install file-saver --save)并在前端组件中导入“saveAs”。
Download(filename){
console.log(filename);
this.fileService.download(filename).subscribe((data)=>{
console.log(data);
saveAs(data, filename);
});
}
组件.ts
download(filename){
const fileObj = {
filename : filename
};
console.log(fileObj);
return this.http.post(`http:localhost:3000/download`, fileObj, {
responseType : 'blob',
});
}
文件服务.ts
app.post('/download', (req, res, next) => {
console.log('here');
filepath = path.join(__dirname,'../uploadedFiles') + '/' + req.body.filename;
console.log(filepath);
res.sendFile(filepath);
});
服务器.js
关于node.js - Angular 下载 node.js response.sendFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56231765/