I'm working on a text editor in pure Javascript. I'd like it so that when the user clicks the 'Save' button, the editor downloads the file. I've already got this partly working:
uriContent = "data:application/octet-stream," + encodeURIComponent(codeMirror.getValue()); newWindow=window.open(uriContent, 'filename.txt');
The file downloads, but the problem is that the file is named 'download'.
Question: How could I change the name of the file to be anything I want, e.g filename.txt
?
Replace your "Save" button with an anchor link and set the new download
attribute dynamically. Works in Chrome and Firefox:
var d = "ha"; $(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");
Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/
Here a compatibility table for download
attribute: http://caniuse.com/download
function saveAs(uri, filename) { var link = document.createElement('a'); if (typeof link.download === 'string') { document.body.appendChild(link); // Firefox requires the link to be in the body link.download = filename; link.href = uri; link.click(); document.body.removeChild(link); // remove the link when done } else { location.replace(uri); } }
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