问题
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)
回答1:
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');
来源:https://stackoverflow.com/questions/12718210/how-to-save-file-from-textarea-in-javascript-with-a-name