我想写数据到现有的文件使用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解决方案的情况下,这肯定是现代浏览器中最好的解决方案,它仍然可以使用这种更简单的方法,顺便说一下,它在文件大小上有限制:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
function download() {
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {
download()
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>