Pawan Singh
Pawan Singh

Reputation: 1227

Download Csv file on front end after clicking on button using angularjs , nodejs ,expressjs

I want to download .csv file on frontend.

this is my code:

$http.get('/entity/consultations/_/registerationReport' )
     .success(function (data) {
         myWindow = window.open('../entity/consultations/_/registerationReport', '_parent');
         myWindow.close();
       });

and I use json2csv converter to write in csv file.

json2csv({data: report, fields: fields}, function (err, csv) {
    if (err) throw err;
    res.setHeader('Content-Type', 'application/csv');
    res.setHeader("Content-Disposition", "attachment; filename=" + "Report.csv");
    res.end(csv, 'binary');
});

but it prints data of csv file on browser instead of downloading csv file.

Upvotes: 3

Views: 1779

Answers (1)

JME
JME

Reputation: 3642

@Pawan, there's nothing wrong with your json2csv function. The issue is the fact that you're trying to trigger the download with an XMLHttpRequest (XHR) request using Angular's $http service. An XHR call suggests that your code will be handling the response from the server. As such the Content-Disposition headers are ignored by the browser and do not trigger a download on the browser.

From what I can tell you have several options:

  1. If you don't have any pre-processing to do on the client, why not just use a direct link to /entity/consultations/_/registerationReport (using and <a> tag),
  2. You may also write $window.open(...) from your Angular code (this will have the ugly side effect of a flashing popup tab or window)

There are probably a number of other solutions, but these are the only ones that immediately come to mind. The bottom line is that XHR is not the right tool for the task you're trying to accomplish.

Upvotes: 1

Related Questions