Reputation: 128
I'm using AngularJS to create a new tag in order to download a csv file. Below the code I use to trigger the download. The download starts on Chrome but not in Firefox. Do you have any clue why this happens?
var element = angular.element('<a/>');
element.attr({
href: exportedString,
target: '_self',
download: 'test.csv'
})[0].click();
EDIT: Firefox needs an existent DOM
JS:
var linkElem = $("#link");
var element = angular.element(linkElem);
HTML:
<a ng-hide=true id="link"></a>
EDIT 2: On Chrome, the downloaded file name is "download" and not the passed value ("test.csv" in this case). Any suggestions?
Here there is also a plunker
Upvotes: 5
Views: 2960
Reputation: 1650
To get both Chrome & FF to work, I actually found that I had to first check to see if element[0] was undefined (which it was in Chrome but not FF):
var link = $("#reportDownloadLink");
var element = angular.element(link)
.attr('href', dataUrl)
.attr('download', data.FileDownloadName)
.attr('target', '_blank');
(element[0] || element).click();
Upvotes: 0
Reputation: 5610
This is a bug in Chrome 35 reported in issue #377860.
Follow this answer for more details
I updated your plunker solution.
Basically you need to use it like follow:
var element = document.createElement('a');
var blob = new Blob([$scope.exportContent], {
type: 'text/csv'
});
var url = URL.createObjectURL(blob);
element.href = url;
element.setAttribute('download', 'test.csv');
document.body.appendChild(element); //Append the element to work in firefox
element.click();
Upvotes: 4