Şahin Ersever
Şahin Ersever

Reputation: 356

How to download file directly in node response in react?

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?

Upvotes: 1

Views: 1159

Answers (1)

Shikhar Awasthi
Shikhar Awasthi

Reputation: 1232

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();
 })

Upvotes: 1

Related Questions