1

How do I download the document I receive in return in react?

Here is the my node.js app. fetchContracts is a function which getting data from mongodb then ganere a excel file by using json2xls npm package.

Its returns as like this:

 const xls = json2xls(contracts); return xls; 

If tying to write file fs.writeFileSync(path.join(__dirname, filename), xls, 'binary'); generating successfully xlsx file in the server.

But I need to send the file to the server without writing file. For this, I made some experiments that you can see below.

export const EXPORT_EXCEL: SessionedAsyncControllerType = async (req: SessionedRequest, res: Response) => { const fileName = 'hello_world.xlsx' const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' const xls = await fetchContracts({}, "fileName.xlsx") const fileData = xls; res.writeHead(200, { 'Content-Disposition': `attachment; filename="${fileName}"`, 'Content-Type': fileType, }) const download = Buffer.from(fileData, 'base64') res.end(download) } 

I getting response like this.

response preview

But i don't know how can i download the response file in react?

In react side:

return api.get(`api/excel`).then((response: any) => { console.log(response); }) 

I just log into console. How can i download directly file which coming node response in react.js?

1

1 Answer 1

1

Try this

return api.get(`api/excel`).then((response: any) => { const outputFilename = `${Date.now()}.xlsx`; // If you want to download file automatically using link attribute. const url = URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', outputFilename); link.click(); }) 
Sign up to request clarification or add additional context in comments.

2 Comments

I returned json object from nodejs then i converted the data to excel format in react.
okay @ŞahinErsever

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.