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

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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
  });

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.