因爲「我們可以假設用戶在最新的Chrome瀏覽器」,這種類型的東西可以通過創建屬性下載<a>
完成和href,然後點擊它。 下面的示例代碼。
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');
你能用php嗎? –
你可以通過指定一個頭來設置文件名,參見[這個問題](http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in -http)。 –
這樣做是在規範但不是可用的,看到這個問題的答案@JeremyJStarcher鏈接到:http://stackoverflow.com/a/10667687/1615483 –