I'm trying to dynamically create data in JavaScript that downloads with a .csv extension, but am unable to associate a filename with the download. Here's a code snippet:
var data = '1,2,3';
window.location =
"data:application/csv;charset=UTF-8;content-disposition:attachment;filename=export.csv,"
+ encodeURIComponent(data);
This downloads, but the file name is generic, without a .csv extension.
I can do this server-side, with the following PHP code:
<?php
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=export.csv');
echo "1,2,3";
?>
Additionally, if my back is to the wall, I can modify my Javascript to send an Ajax out to the server and get this in return, but I'd prefer a pure Javascript solution. Is there a browser-independent, Flash-free way of doing this?
EDIT
Someone pointed out this question as a possible duplicate. I did goo-diligence and checked previous SO articles. I am still asking this because some time has passed since those questions, so I am hoping:
- Browser features may have changed favorably.
- Older browsers are less of a constraint, so certain solutions may be more viable now than when the previous questions were asked.
Additionally, if it makes the question more palpatable, I'm specifically asking about inserting a type of content header into a data URI (as per the subject), which is a twist on the other questions.
Thanks in advance.