JavaScript:文件保存自動下載函數:Save和SaveAs
/* Save函數和SaveAs函數 */ /* Save函數 * 使用:save(data).as(type) 或 save(data).name(name).as(type) */ function Save(data) {this.data=data;this.fileName="data"} Save.prototype.as=function(type) { var link = document.createElement("a") var url = 'data:text/'+type+';charset=utf-8,\uFEFF' + encodeURI(this.data); link.href = url; link.download = this.fileName+"."+type; link.click(); } Save.prototype.name=function(param) { this.fileName=param; return this; } var save=function(data){return new Save(data)};
/* SaveAs函數 使用:第一個參數是要保存的數據,第二個參數是要保存的類型 */ function SaveAs(data,type,name) { var link = document.createElement("a"); var exportName=name?name:'data'; var url = 'data:text/'+type+';charset=utf-8,\uFEFF' + encodeURI(data); link.href = url; link.download = exportName+"."+type; link.click(); }