Angular download node.js response.sendFile

五迷三道 提交于 2019-12-11 16:21:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!