2014-10-09 14 views
1

我想使用JavaScript中的File API來將生成的內容存儲在客戶端瀏覽器的文件系統上。我查看了文檔,但沒有發現跨瀏覽器的解決方案(FileSystem API似乎只是Chrome)。使用File API編寫javascript生成的文件

隨着文件API:作家正在停產,我不知道我有什麼選擇。有什麼建議麼?

+1

[似乎得到廣泛支持(http://caniuse.com/#feat=fileapi) – 2014-10-09 09:16:13

+0

爲什麼不使用Web存儲API? – 2014-10-09 09:32:12

回答

0

我發現以下解決方案很簡單,似乎很好地解決了我的問題。有了這個,我可以生成一個文件並提供下載鏈接,以便用戶保存。下面是示例代碼我使用:

HTML

<!DOCTYPE html> 
<html> 
<head> 
</head> 
<body> 
<textarea id="fileContent" type="text" cols=80 rows=30>File Content!</textarea> 
<a id="anchor" href="#" download="fileContent.txt">Download Me!</a> 
<script src="clientfile.js"></script> 
</body> 
</html> 

的JavaScript

var fileContent = document.getElementById("fileContent"); 
var anchor = document.getElementById("anchor"); 

anchor.onclick = function() { 
    var fileContent_blob = new Blob([fileContent.value], {type: 'text/plain'}); 
    if (window.navigator.msSaveBlob === undefined) { 
     anchor.setAttribute('href', URL.createObjectURL(fileContent_blob)); 
    } 
    else { 
     window.navigator.msSaveOrOpenBlob(fileContent_blob, 'fileContent.txt'); 
    } 
} 
0

您寫的文字時只是在Chrome中支持FileSystem API是正確的,它可能不會在其他瀏覽器中實現。

http://caniuse.com/#feat=filesystem

每MDN,文件系統API不應該在生產中使用:

此功能是非標準的,而不是一個標準的軌道。不要在面向Web的生產站點上使用它:它不適用於每個用戶。實現之間也可能存在很大的不兼容性,並且行爲在未來可能會發生變化。

目前更好的支持選項,以在客戶端存儲的文件有:

  1. Web存儲API - http://caniuse.com/#feat=namevalue-storage
  2. 餅乾
  3. IndexedDB的 - http://caniuse.com/#feat=indexeddb
  4. 的WebSQL數據庫 - http://caniuse.com/#feat=sql-storage