在浏览器中保存本地文件1

更新:大部分浏览器的最新版本都支持通过 Blob 来保存本地文件,具体方法见这里

前一篇已经总结了在浏览器中打开本地文件的方法,现在接着总结保存本地文件的方法,同样以保存 textarea 的内容到本地文件为例。

首先还是 IE,IE 的 document.execCommand 函数中可以使用 SaveAs 参数来将当前网页保存到本地文件。我们利用 iframe 就可以实现保存 textarea 内容到文件的目的。例子如下:

<html>
<body>
<textarea id="areaid">hello this!</textarea>
<button onclick="doSave()">Save</button>
<script type="text/javascript">
// works in ie
function doSave(){
var myarea = document.getElementById("areaid");
var w = document.createElement("iframe");
w.id = "w";
w.style.display = "none";
document.body.insertBefore(w, null);
var b = window.frames.w;
b.document.open();
b.document.write(myarea.value);
b.document.close();
b.document.execCommand("SaveAs", false, "filename.txt");
b.close();
document.body.removeChild(w);
}
</script>
</body>
</html>

上面代码还有点问题:textarea的换行符在保存时丢失了。因此还需要改进一下。

接下来我们来看看 Firefox 的情形。在 Firefox 中我们可以用 data URI 方式来实现文本框内容的保存:

<html>
<body>
<textarea id="areaid">hello this!</textarea>
<button onclick="doSave()">Save</button>
<script type="text/javascript">
function doSave() {
// works in firefox, and chrome 11
var text = document.getElementById("areaid").value;
var data = "data:x-application/text,"+encodeURIComponent(text);
window.open(data);
}
</script>
</body>
</html>

上述的代码在 Chrome 11 中也能正常运行。

参考资料:

[1] MSDN - SAVEAS Command
[2] Writing to the local file system - 4umi useful Javascript
[3] CExplorer: Save Text Files with JavaScript
[4] Javascript - Save file?
[5] Browser - file writer extension?
[6] How to create a file using javascript in Mozilla Firefox

[YAML] Date: 2011-05-26 19:37:49, Updated: 2013-02-08 11:00:00

原文地址:https://www.cnblogs.com/zoho/p/2432151.html