我想写数据到现有的文件使用JavaScript。
我不想在主机上打印。
我想实际写入数据到abc.txt。
我读了很多回答的问题,但他们都是在主机上打印的。
在某些地方,他们给出了代码,但它不起作用。
所以请任何人可以帮助我如何实际写入数据文件。
我引用了代码,但它不工作:
给出错误:
Uncaught TypeError:非法构造函数
在chrome和
SecurityError:操作不安全。
在Mozilla
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
所以我们实际上可以写数据到文件只使用Javascript或不?
我在这里找到了很好的答案,但也找到了更简单的方法。
创建blob的按钮和下载链接可以组合在一个链接中,因为link元素可以有一个onclick属性。(反过来似乎是不可能的,在按钮上添加href是行不通的。)
您可以使用bootstrap将链接设置为按钮样式,这仍然是纯javascript,除了样式。
结合按钮和下载链接还可以减少代码,因为需要的丑陋的getElementById调用更少了。
这个例子只需要点击一个按钮来创建text-blob并下载它:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>