2012-11-15 82 views
147

我有要寫入文件的數據,並打開文件對話框供用戶選擇保存文件的位置。如果它在所有的瀏覽器中都能正常工作,但它必須在Chrome中運行。我想在客戶端完成這一切。JavaScript:創建並保存文件

基本上我想知道要放什麼東西在這個函數:

saveFile: function(data) 
{ 
} 

當函數取數據,讓用戶選擇一個位置來保存文件,並創建一個文件,在該位置與數據。

使用HTML也很好,如果有幫助。

+56

「基本上我想知道該怎麼把這個功能:」每一個好問題的實質! –

+3

已經[在內存中爲用戶下載,而不是通過服務器創建一個文件]的確切副本(http://stackoverflow.com/questions/3665115/create-a-file-in-memory-for-user-to -download-not-through-server)多年。 –

回答

6

你不能這樣做純粹在Javascript中。由於安全原因,運行在瀏覽器上的Javascript還沒有足夠的權限(有提議)。

相反,我會建議使用Downloadify

一個微小的JavaScript + Flash庫,使創建和文本文件沒有下載服務器交互。

您可以看到一個簡單的演示here您可以在其中提供內容並可以測試保存/取消/錯誤處理功能。

13

對於最新的瀏覽器,如Chrome,你可以使用File API as in this tutorial

window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; 
window.requestFileSystem(window.PERSISTENT, 5*1024*1024 /*5MB*/, saveFile, errorHandler); 
+2

我認爲[這段代碼片段](http://www.html5rocks.com/en/tutorials/file/filesystem/#toc-file-writing)會更接近提問者的意圖。 –

+2

在這裏看到的證據是deadness:http://lists.w3.org/Archives/Public/public-webapps/2014AprJun/0010.html – voidstate

109

在github上這個項目看起來很有希望:

https://github.com/eligrey/FileSaver.js

FileSaver.js實現了W3C的saveAs( ) 中的FileSaver界面本身不支持它。

也看看這裏的演示:

http://eligrey.com/demos/FileSaver.js/

+22

http://www.w3.org/TR/file-writer-api /#the-filesaver-interface說:「關於本文檔的工作已經停止,不應該被引用或用作實現的基礎。」 – Godsmith

+1

不適用於safari – fdrv

+0

「實現w3C saveAs」???那是什麼?該演示是無用的,沒有代碼。 – CashCow

36

選擇的位置,將文件保存在創建它是不可能的了。但至少在Chrome中,可以使用JavaScript來生成文件。以下是我創建CSV文件的一箇舊例子。用戶將被提示下載它。不幸的是,這在其他瀏覽器中效果不佳,尤其是IE瀏覽器。

<!DOCTYPE html> 
<html> 
<head> 
    <title>JS CSV</title> 
</head> 
<body> 
    <button id="b">export to CSV</button> 
    <script type="text/javascript"> 
     function exportToCsv() { 
      var myCsv = "Col1,Col2,Col3\nval1,val2,val3"; 

      window.open('data:text/csv;charset=utf-8,' + escape(myCsv)); 
     } 

     var button = document.getElementById('b'); 
     button.addEventListener('click', exportToCsv); 
    </script> 
</body> 
</html> 
+1

當我使用它時,它會打開一個帶有文本的新選項卡,它不打開文件對話窗口。 – user1756980

+0

@ user1756980 - 是的。您需要從該新標籤中「保存到文件」。 –

+0

它取決於瀏覽器,操作系統等。在我寫回答的時候,Chrome中的csv數據網址會彈出一個保存對話框 –

80

function download(text, name, type) { 
 
    var a = document.getElementById("a"); 
 
    var file = new Blob([text], {type: type}); 
 
    a.href = URL.createObjectURL(file); 
 
    a.download = name; 
 
}
<a href="" id="a">click here to download your file</a> 
 
<button onclick="download('file text', 'myfilename.txt', 'text/plain')">Create file</button>

然後您可以通過將下載屬性錨標記上下載文件。

我喜歡這個比創建數據網址更好的原因是,您不必製作一個很長的網址,只需生成一個臨時網址即可。

+0

@Banjocat你應該檢查瀏覽器是否支持某些對象。示例檢測:'if(「URL」在窗口中&&「createObjectURL」在URL中&&「在Element.prototype中下載」):else然後您只需更改下載方法或注意瀏覽器不支持所需的對象來下載文件。 – Hydro

7

在控制檯嘗試了這一點,它的工作原理。

var aFileParts = ['<a id="a"><b id="b">hey!</b></a>']; 
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob 
window.open(URL.createObjectURL(oMyBlob)); 
101

一個很小的改進代碼的Awesomeness01(無需錨標籤)與另外由trueimage(IE瀏覽器支持)建議:

// Function to download data to a file 
function download(data, filename, type) { 
    var file = new Blob([data], {type: type}); 
    if (window.navigator.msSaveOrOpenBlob) // IE10+ 
     window.navigator.msSaveOrOpenBlob(file, filename); 
    else { // Others 
     var a = document.createElement("a"), 
       url = URL.createObjectURL(file); 
     a.href = url; 
     a.download = filename; 
     document.body.appendChild(a); 
     a.click(); 
     setTimeout(function() { 
      document.body.removeChild(a); 
      window.URL.revokeObjectURL(url); 
     }, 0); 
    } 
} 

測試在Chrome中正常地工作, FireFox和IE10。

在Safari中,得到的數據在新標籤打開,一個必須手動保存這個文件。

+1

具體是哪個版本的IE? –

+0

@Soren據我所知,它目前在任何版本的IE中都不起作用。 Safari也許沒有它,但我不與這些工作,我將不得不查找它。 – Awesomeness01

+0

不適用於Google Chrome。我正在考慮把它作爲一個小書籤 'javascript:function download(text,name,type)var a = document.getElementById(「content」); var file = new Blob([text],{type:type}); a.href = URL.createObjectURL(file); a.download = name; }' – Jeno

9

setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')"); 
 
function create(text, name, type) { 
 
    var dlbtn = document.getElementById("dlbtn"); 
 
    var file = new Blob([text], {type: type}); 
 
    dlbtn.href = URL.createObjectURL(file); 
 
    dlbtn.download = name; 
 
}
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>

0

對於Chrome和Firefox,我一直在使用純JavaScript方法。

(我的應用程序不能利用的包裝,如Blob.js,因爲它是從一個特殊的發動機服務:在和小房間的東西擠在全部WWWeb服務器DSP)

function FileSave(sourceText, fileIdentity) { 
    var workElement = document.createElement("a"); 
    if ('download' in workElement) { 
     workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText); 
     workElement.setAttribute("download", fileIdentity); 
     document.body.appendChild(workElement); 
     var eventMouse = document.createEvent("MouseEvents"); 
     eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 
     workElement.dispatchEvent(eventMouse); 
     document.body.removeChild(workElement); 
    } else throw 'File saving not supported for this browser'; 
} 

注意事項,注意事項和黃鼠狼字:

  • 我在Linux(Maipo)和Windows(7和10)環境中運行的Chrome和Firefox客戶端都已成功使用此代碼。
  • 但是,如果sourceText大於MB,則Chrome有時(有時)會在自己的下載中卡住而沒有任何故障指示;到目前爲止,Firefox尚未展現出這種行爲。原因可能是Chrome中的一些blob限制。坦率地說,我只是不知道;如果任何人有任何想法如何糾正(或至少檢測),請張貼。如果下載發生異常時,當Chrome瀏覽器被關閉時,它產生一個診斷如 Chrome browser diagnostic
  • 此代碼不與邊緣或Internet Explorer兼容;我還沒有試過Opera或Safari。
相關問題