Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file Javascript with file name [duplicate]

Tags:

javascript

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?

like image 436
skimberk1 Avatar asked Oct 10 '11 19:10

skimberk1


2 Answers

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 downloadattribute: http://caniuse.com/download

like image 58
Arthur Clemens Avatar answered Sep 29 '22 23:09

Arthur Clemens


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);     } } 
like image 26
Reddy Avatar answered Sep 29 '22 23:09

Reddy