2013-03-05 121 views

回答

2

目前File API: Writer還沒有準備好,所以你沒有直接的接口來保存文件。

不過,您可以創建一個鏈接並將文本放入網址中。

var link = document.createElement('a'); 
link.href = 'data:text/plain;charset=UTF-8,' + encodeURIComponent(yourTextGoesHere); 
link.innerHtml = 'Open the text file'; 
//set default action on link to force download, and set default filename: 
link.download = 'some file name.txt';  

//now put the link somewhere in the html document: 
document.body.appendChild(link); 

用手書寫而未經測試。應該可以工作,但可能需要調試。

編輯: 加入download屬性。

+0

是否可以在生成文件後打開savefile對話框? – arrowman 2017-01-13 08:23:27

+0

您可以添加'download =「some file name.txt」'強制下載文件,但大多數瀏覽器只會下載它,而不會詢問文件的保存位置。 我在這裏提到的FileWriter API似乎已被W3C終止,並且,雖然它在Chrome中受支持,但它可能會被丟棄,所以我不會使用它。 http://caniuse.com/#feat=filesystem – SWilk 2017-01-16 13:28:14