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
?
This question is related to
javascript
Use the filename
property like this:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
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);
}
}
Source: Stackoverflow.com