Skip to content Skip to sidebar Skip to footer

How To Give Download Window Option To User In A Node.js Express Application

I am building a node.js + express application. An excel file gets created on my server side and I need to serve it to the user in the download window. So the user can choose his de

Solution 1:

The first advice is to stop storing the file with your code if it's not meant to last long. A better approach will be to use the temporal directory of the machine and letting the OS clean for you. You can use tempfile in order to generate a full path to a temporal file.

The second advice is to avoid splitting the file generation and download steps. You can use res.download() api on the server to instruct the browser into presenting the download windows directly to the user. That is: instead of sending to the browser the file name to download on the next step, you send directly the file content to download and a special header to instruct the client browser you want the client to download the file.

The latter require you to modify the Jquery(?, correct me if i'm wrong here) code on the browser. Once the post request is made and the server response is received the browser should present the download dialog directly.

Try this:

var tmp = tempfile('.xlsx');
workbook.xlsx.writeFile(tmp).then(function() {
    console.log('file is written');
    res.download(tmp, function(err){
        console.log('---------- error downloading file: ' + err);
    });
});

Post a Comment for "How To Give Download Window Option To User In A Node.js Express Application"