I am exporting data using javascript to csv. for some reason i am not allowed to use the traditional
<a download="filename.csv" /a>
to set the file name.
I have the following line of code:
window.location.href = "data:text/csv;base64," + csvdata
Where and how can i insert and specify the file name and extension to make it work?
I am exporting data using javascript to csv. for some reason i am not allowed to use the traditional
<a download="filename.csv" /a>
to set the file name.
I have the following line of code:
window.location.href = "data:text/csv;base64," + csvdata
Where and how can i insert and specify the file name and extension to make it work?
Share Improve this question edited Oct 16, 2015 at 23:25 WABBIT0111 asked Oct 16, 2015 at 23:09 WABBIT0111WABBIT0111 2,3134 gold badges20 silver badges30 bronze badges 1- FYI, i am using Angular. with ng-click to trigger a function. due to some aspect, i would not and cannot create a <a> tag in place. thus would there be another way to just specify in window.location.href to specify the filename? – WABBIT0111 Commented Oct 16, 2015 at 23:25
1 Answer
Reset to default 12It's not possible that way, try to emulate the <a href=..
with a click on it like this:
var csvdata = "Hello World"; // only for test
var byteNumbers = new Uint8Array(csvdata.length);
for (var i = 0; i < csvdata.length; i++)
{
byteNumbers[i] = csvdata.charCodeAt(i);
}
var blob = new Blob([byteNumbers], {type: "text/csv"});
// Construct the uri
var uri = URL.createObjectURL(blob);
// Construct the <a> element
var link = document.createElement("a");
link.download = 'myfile.csv';
link.href = uri;
document.body.appendChild(link);
link.click();
// Cleanup the DOM
document.body.removeChild(link);
delete link;