Download text/csv content as files from server in Angular

angularjs, http, http-headers, javascript, node.js

Solution

`$http` service returns a `promise` which has two callback methods as shown below.

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // handle error
  });

Problem

I am trying to stream a `csv` file from a node.js server. The server portion is very simple : ``` server.get('/orders' function(req, res) { res.setHeader('content-type', 'text/csv'); res.setHeader('content-disposition', 'attachment; filename='orders.csv'); return orders.pipe(res); // assuming orders is a csv file readable stream (doesn't have to be a stream, can be a normal response) } ``` In my angular controller I am trying to do something like this ``` $scope.csv = function() { $http({method: 'GET', url: '/orders'}); }; ``` This function is called when there's a click on a button with `ng-click` in my view : ``` <button ng-click="csv()">.csv</button> ``` I have looked at other answers about downloading files from server in Angular, but didn't find anything that worked for me. Is there a common way to do this ? Seems like something that should be simple.

Original source

Related problems