Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download text/csv content as files from server in Angular not working in Mozilla FireFox

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

like image 888
Komal Singh Avatar asked Dec 25 '22 16:12

Komal Singh


2 Answers

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

like image 105
initialxy Avatar answered Jan 05 '23 16:01

initialxy


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

like image 27
maciejlesniak Avatar answered Jan 05 '23 17:01

maciejlesniak