Javascript:创build并保存文件

我有要写入文件的数据,并打开文件对话框供用户select保存文件的位置。 如果它在所有的浏览器中都能正常工作,但是它必须在Chrome中运行。 我想在客户端做所有的事情。

基本上我想知道该怎么把这个function:

saveFile: function(data) { } 

在函数接收数据的地方,用户select一个位置来保存文件,并用该数据在该位置创build一个文件。

提前致谢。

编辑:使用HTML也好,如果有帮助。

github上的这个项目看起来很有前景:

eligrey/FileSaver.html

FileSaver.js在不支持本机的浏览器中实现W3C saveAs()FileSaver接口。

另外看看这里的演示:

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

由真实图像 (支持IE)build议的Awesomeness01 (不需要锚标记)代码的一个非常小的改进:

 // 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); } } 

testing在Chrome,FireFox和IE10中正常工作。

在Safari中,数据会在新标签页中打开,并且必须手动保存此文件。

 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> 

在创build之前select保存文件的位置是不可能的。 但是,至less在Chrome中,可以使用JavaScript来生成文件。 这是我创buildCSV文件的一个老例子。 用户将被提示下载。 不幸的是,这在其他浏览器,特别是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> 

对于Chrome等最新的浏览器,您可以使用本教程中的File API :

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

你不能在Javascript中完成这个工作。 由于安全原因,在浏览器上运行的Javascript还没有足够的权限(有提议)。

相反,我会build议使用Downloadify :

一个小巧的JavaScript + Flash库,可以在不需要服务器交互的情况下创build和下载文本文件。

您可以在这里看到一个简单的演示,您可以在其中提供内容,并可以testing保存/取消/error handlingfunction。

在控制台尝试了这一点,它的工作原理。

 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)); 
 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> 

Javascript有一个FileSystem API。 如果您可以处理该function只能在Chrome中运行,那么一个好的起点就是: http : //www.html5rocks.com/en/tutorials/file/filesystem/ 。