0

Possible Duplicate:
Using HTML5/Javascript to generate and save a file

I want a client side HTML/JS solution to solve this problem - I have a user-edittable textarea A, a textfield B and a button C. When user clicks on C, she gets a file download with name equal to B.value and contents equal to A.value. I looked at this but it does not specify how to set the filename and I don't want a Flash solution like this. We can assume users are on latest Chrome browser (it's a little tool for my team)

Community
  • 1
  • 1
pathikrit
  • 29,060
  • 33
  • 127
  • 206
  • You can set the filename by specifying a header, see [this question](http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http). – Manuel Leuenberger Oct 03 '12 at 23:27
  • 1
    Doing this is in the spec but not avalible yet, see this answer to the question @JeremyJStarcher linked to: http://stackoverflow.com/a/10667687/1615483 – Paul S. Oct 03 '12 at 23:41

1 Answers1

4

Because "we can assume users are on latest Chrome browser", this type of thing can be done by creating an <a> with attributes download and href, and then clicking on it. Example code below.

var Download = {
    click : function(node) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        return node.dispatchEvent(ev);
    },
    encode : function(data) {
            return 'data:application/octet-stream;base64,' + btoa( data );
    },
    link : function(data, name){
        var a = document.createElement('a');
        a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1);
        a.href = data || self.location.href;
        return a;
    }
};
Download.save = function(data, name){
    this.click(
        this.link(
            this.encode( data ),
            name
        )
    );
};

Download.save('hello world', 'my_file.txt');
Paul S.
  • 58,277
  • 8
  • 106
  • 120