问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/56231765/angular-download-node-js-response-sendfile