1

I have a controller method in my inversify-express-utils app that looks something like this:

return await this.downloadReportUseCase.invoke(String(req.query.report_id), String(req.query.user_id))
            .then(async ([filename, filedata]: [string, string]) => {
                return res.status(200).sendFile(fs.writeFileSync(filename, filedata)); // I want to do something like this
            })
            .catch((err: Error) => {
                res.status(500).json(err);
            });

Note the comment, how do i achieve something like that? I don't actually want to create a file on the server, i just want a the variable to be sent to the end user in the form of a file that is either XML or CSV file type.

Bebet
  • 199
  • 2
  • 12

2 Answers2

1

With fs.writeFileSync you do actually create a file on the server. Instead, use

res.set("Content-Disposition", "attachment; filename=" + filename);
res.end(filedata);
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
  • With this im getting the data through to the client but im not getting a file download, its just in the response. How do i get a file to download onto the client machine with this data in? – Bebet Apr 30 '22 at 08:40
  • The `Content-Disposition` header causes (my) browser to download the file. – Heiko Theißen Apr 30 '22 at 09:12
1

A combination of this question: How to download files using axios

and using res.attachment in my controller allowed me to download the file

Bebet
  • 199
  • 2
  • 12