Save file Javascript with file name [duplicate]

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());, '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:

Here a compatibility table for downloadattribute:


Use the filename property like this:

uriContent = "data:application/octet-stream;filename=filename.txt," + 
              encodeURIComponent(codeMirror.getValue());, 'filename.txt');


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 === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body = filename;
        link.href = uri;;
        document.body.removeChild(link); // remove the link when done
    } else {


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.