JavaScript - TextArea 文字存成 檔案

摘要:JavaScript - TextArea 文字存成 檔案

參考

http://stackoverflow.com/questions/12718210/how-to-save-file-from-textarea-in-javascript-with-a-name

 

搭配JQuery 撰寫

 

<script>

 

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
        )
    );
};

</script>

 

    <textarea id="data" rows="20" cols="80"></textarea>
    <br/>
    <input type="text" id="filename" size="20"><button onclick="Download.save($('#data').val(),$('#filename').val());return false;">存檔</button>