Angular 下载 node.js response.sendFile [英] Angular download node.js response.sendFile
问题描述
目前我的 nodejs 服务正在这样做:
<预><代码>...fs.writeFileSync('filelocation/data.xlsx', theData, 'binary');response.sendFile('filelocation/data.xlsx');response.download('文件位置/数据.xlsx');//我也试过这个...但是现在如何使用 HttpClient
从 Angular 前端下载它?这不起作用:
this.httpclient.get(url).subscribe(response => {控制台日志(响应);//或者我需要做的任何事情来下载文件});
我希望调用能够打开文件资源管理器,以便我可以保存文件.我如何让这个工作?如果您需要我提供更多信息,请告诉我.
创建一个 component.ts 并将文件名传递给 fileService.在 fileService 内部创建下载函数并使用该函数将文件名传递给后端服务器.可以使用另存为"下载文件.安装文件保护程序(npm install file-saver --save)并在前端组件中导入saveAs".
下载(文件名){控制台日志(文件名);this.fileService.download(filename).subscribe((data)=>{控制台日志(数据);另存为(数据,文件名);});}
组件.ts
下载(文件名){const fileObj = {文件名:文件名};控制台日志(fileObj);返回 this.http.post(`http:localhost:3000/download`, fileObj, {响应类型:'blob',});}
fileService.ts
app.post('/download', (req, res, next) => {console.log('这里');filepath = path.join(__dirname,'../uploadedFiles') + '/' + req.body.filename;控制台日志(文件路径);res.sendFile(文件路径);});
Server.js
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
...
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.
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
download(filename){
const fileObj = {
filename : filename
};
console.log(fileObj);
return this.http.post(`http:localhost:3000/download`, fileObj, {
responseType : 'blob',
});
}
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
这篇关于Angular 下载 node.js response.sendFile的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!