角下载node.js response.sendFile [英] Angular download node.js response.sendFile
问题描述
目前,我的nodejs服务正在执行此操作:
At the moment my nodejs service is doing this:
...
fs.writeFileSync('filelocation/data.xlsx', theData, 'binary');
reponse.sendFile('filelocation/data.xlsx');
reponse.download('filelocation/data.xlsx'); // I tried this one also
...
但是现在如何使用HttpClient
从Angular前端下载此文件?这不起作用:
But now how do I download this from Angular front end using the HttpClient
? This does not work:
this.httpclient.get(url).subscribe(response => {
console.log(response); // Or whatever I need to do to download the file
});
我希望该呼叫调出文件浏览器,以便我可以保存文件.我该如何工作?如果您需要我的更多信息,请告诉我.
I want the call to bring up the file explorer so that I can save the file. How do I get this working? If you need more info from me just let me know please.
推荐答案
创建一个component.ts并将文件名传递给fileService. 在fileService内部创建下载功能,并使用该功能将文件名传递给后端服务器.可以使用"saveAs"下载文件.安装filesaver( npm install file-saver --save ),然后在前端组件中导入"saveAs".
create a component.ts and pass filename to fileService. inside fileService create download function and using that pass the filename to backend server. File can be downloaded using 'saveAs'. Install filesaver (npm install file-saver --save) and import 'saveAs' in frontend component.
Download(filename){
console.log(filename);
this.fileService.download(filename).subscribe((data)=>{
console.log(data);
saveAs(data, filename);
});
}
Component.ts
Component.ts
download(filename){
const fileObj = {
filename : filename
};
console.log(fileObj);
return this.http.post(`http:localhost:3000/download`, fileObj, {
responseType : 'blob',
});
}
fileService.ts
fileService.ts
app.post('/download', (req, res, next) => {
console.log('here');
filepath = path.join(__dirname,'../uploadedFiles') + '/' + req.body.filename;
console.log(filepath);
res.sendFile(filepath);
});
Server.js
Server.js
这篇关于角下载node.js response.sendFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!