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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With