我想使用 JavaScript 将数据写入现有文件。
我不想在控制台上打印它。
我想实际将数据写入 abc.txt
。
我阅读了许多已回答的问题,但他们在控制台上打印的每个地方。
在某些地方,他们已经给出了代码,但它不起作用。
所以请任何人帮助我如何实际将数据写入文件。
我引用了代码,但它不起作用: 它的错误:
Uncaught TypeError: Illegal constructor
在 Chrome 和
SecurityError: The operation is insecure.
在 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 或不使用 Javascript 将数据写入文件吗?
最佳答案
您可以使用 Blob
在浏览器中创建文件和 URL.createObjectURL
.所有最近的浏览器support this .
您不能直接保存您创建的文件,因为这会导致严重的安全问题,但您可以将其作为下载链接提供给用户。您可以通过 download
attribute 建议文件名链接的,在支持下载属性的浏览器中。与任何其他下载一样,下载文件的用户将对文件名拥有最终决定权。
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
这是 example使用这种技术保存 textarea
中的任意文本。
如果您想立即启动下载而不是要求用户点击链接,您可以使用鼠标事件来模拟鼠标点击链接,如 Lifecube的answer做过。我创建了一个 updated example使用这种技术。
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
关于javascript - 是否可以仅使用 JavaScript 将数据写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012580/