4

Download text/csv content as files from server in Angular

Answered By - https://stackoverflow.com/users/2064206/dcodesmith

$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) {
    // if there's an error you should see it here
  });

I implemented this solution for downloading files from server to client using angular. This is perfectly working fine in Google chrome. But this Solution is not working in Mozilla Firefox.

Thanks

Community
  • 1
  • 1
Komal Singh
  • 451
  • 5
  • 19

4 Answers4

9

You have to attach the anchor you created to your document first. Add the followings:

var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document

anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

anchor.remove(); // Clean it up afterwards

Fiddle

initialxy
  • 1,193
  • 8
  • 17
1

You should use encodeURIComponent() instead of encodeURI() - because of better encoding of characters like #, &, =. See documentation on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
0

Just to recap, the solution that worked for me is (using encodeURIComponent as maciejlesniak suggested):

$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document

anchor.attr({
    href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
    target: '_blank',
    download: 'filename.csv'
})[0].click();

anchor.remove(); // Clean it up afterwards

  }).
  error(function(data, status, headers, config) {
    // if there's an error you should see it here
  });
0

You can also work around something like this.

var anchor = angular.element('<a/>');
anchor.attr({
  href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
  target: '_blank',
  download: 'filename.csv'
});
var click = new MouseEvent('click', {
      'view': window,
      'bubbles': true,
      'cancelable': true
  }); 
anchor[0].dispatchEvent(click);

This should work Firefox as well, without attaching the anchor tag on the document.body

sajan
  • 1,355
  • 1
  • 14
  • 19