Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i generate a file and offer it for download in plain javascript?

I would like to generate a text file in the javascript dynamicly, then offer this for download. Currently I can get this working to a degree with either of the following solutions:

content = "abc123";
document.location = "data:text/octet-stream," + encodeURIComponent(content);

OR

content = "abc123";    
var bb = new BlobBuilder();
bb.append(content);
var blob = bb.getBlob();
blob = blob.slice(0, blob.size, 'text/octet-stream');
var fr = new FileReader(); 
fr.onload = function() {document.location = this.result;}
fr.readAsDataURL(blob);

However, Both of these solutions, when the download box appears, will only offer a default filename of 'download' in the save as dialogue.

My question is basically, how can I change this to a specific filename for example 'readme.txt' or 'scene.obj'

Also note the data type was previously 'text/plain' however if this is used, the document switches to the new text document instead of offering it for download (as text/octet-stream seems to do).

I do not want a flash solution, javascript/html5 only suggestions please.

Cheers, Josh

like image 439
Josh Mc Avatar asked May 30 '11 11:05

Josh Mc


1 Answers

For that, you will have to use FileSaver from FileAPI: Writer specification. For now, it's only a draft, and according to mailing list answer it isn't yet implemented in browsers.

You can watch for example on a chromium issue to get up-to-date information about the implementation progress

UPD 02.08.2013: I have since found a project that provides FileSaver interface using neat tricks

like image 65
Alexander Avatar answered Sep 28 '22 00:09

Alexander