3

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.

Paul Kruger
  • 2,094
  • 7
  • 22
  • 49
  • This link may help https://stackoverflow.com/questions/35138424/how-do-i-download-a-file-with-angular2/51994086 – Ameerudheen.K May 21 '19 at 06:31
  • Is it not logging the response or is it logging the response but you have no idea how to open the save dialog (open the file explorer)? -- the solutions to the two conditions are vastly different – slebetman May 21 '19 at 07:07

1 Answers1

2

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

Paul Kruger
  • 2,094
  • 7
  • 22
  • 49
shreyas-agrawal
  • 244
  • 2
  • 5