Tikkes
Tikkes

Reputation: 4689

NodeJS - prompt download CSV file

I'm trying to get - after some promises have been executed - a CSV result back together with a status reponse having details.

The response does get me the data for the CSV but I cannot seem to get the browser to download this data into a CSV file.

router.post('/getSalesOrders', function (request, response) {
    var data = request.body;
    salesOrderActions.retrieveSalesOrders(data) //
        .then(function (result) {
            response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
            response.set('Content-Type', 'text/csv');
            response.json(result[0].message).send(result[0].file);
        })
        .catch(function (err) {
            console.log(err);
            if (err.statusCode) {
                response.json(err);
            }
            else {
                var error = output.getCriticalErrorResult(c.titles.SERVICE_CRITICAL_ERROR, c.messages.UNKNOWN_ERROR, err.message);
                response.json(error);
            }
        });
});

My result object gets created in the salesOrderActions:

I am here using npm package json2csv

var fields = ['id',.....];
var csv = csvParser({ data: unmatchedLines, fields: fields });

return {
     file: csv,
     message:
         output.getSuccessResult(
             titles.SALES_ORDER_SUCCESS_RETRIEVAL,
             salesDataForModel.identifier
         )
}

My response to the browser is as follows: enter image description here enter image description here

So my message isn't sent it seems and I do get the CSV data but not as a file to download. How can I manage that?

As a sidenote maybe, my front-end is React

EDIT

Response with octed headers:

enter image description here enter image description here

Upvotes: 1

Views: 4625

Answers (3)

Tikkes
Tikkes

Reputation: 4689

So actually it turns out it is because I'm doing an Ajax request which doesn't - by default - prompt the browser to download any files.

What I did in the end:

router.post('/getSalesOrders', function (request, response) {
    var data = request.body;
    salesOrderActions.retrieveSalesOrders(data)
        .then(function (result) {
            response.json(result);
        })
        .catch(function (err) {
            //...
        });
});

And then in my front-end, when receiving the result:

salesOrderService.retrieveSalesOrderData()
.then(function (result) {
    self.convertAndDownloadCsv(result.unmatchedLines);
});

convertAndDownloadCsv: function (data) {
    if (data && data.length > 0) {
        var csvData = csvProcessor({ //using csv2json node js package
            data: data,
            quotes: '',
            del: ';'
        });
        var filename = "unmatchedLinesFromSalesOrders.csv";
        var blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
}

More info can be found here

Upvotes: 1

filippo
filippo

Reputation: 3077

Try:

  • sending Content-Type before Content-Disposition
  • quoting the filename: filename="testing.csv"

Also HTTP headers are case insensitive, so it should not make a difference, but you should write Content-Disposition (capital D).

response.set('Content-Type', 'text/csv');

response.setHeader('Content-Disposition', 'attachment; filename="testing.csv"');

If this does not work you can change the Content-Type to application/octet-stream

This always forces the browser to download the data sent from the server.

Upvotes: 2

Ediruth
Ediruth

Reputation: 168

Try this code:

router.post('/getSalesOrders', function (request, response) {
    var data = request.body;
    var fs = require('fs');

   salesOrderActions.retrieveSalesOrders(data) //
    .then(function (result) {
       //**********
        var file = "testing.csv";
        response.setHeader('Content-disposition', 'attachment; filename=testing.csv');
        response.set('Content-Type', 'text/csv');
        var filestream = fs.createReadStream(file);
        filestream.pipe(res);
       //*********
    })
    .catch(function (err) {
        console.log(err);
        if (err.statusCode) {
            response.json(err);
        }
        else {
            var error = output.getCriticalErrorResult(c.titles.SERVICE_CRITICAL_ERROR, c.messages.UNKNOWN_ERROR, err.message);
            response.json(error);
        }
    });
});

Upvotes: 1

Related Questions