我想写数据到现有的文件使用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或不?


当前回答

使用上面用户@useless-code (https://stackoverflow.com/a/21016088/327386)的代码来生成文件。 如果你想自动下载文件,将刚刚生成的textFile传递给这个函数:

var downloadFile = function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
}

其他回答

对此,我有一些建议

如果你试图在客户端机器上写一个文件,你不能在任何跨浏览器的方式这样做。IE确实有一些方法可以让“受信任的”应用程序使用ActiveX对象来读写文件。 如果您试图将其保存在服务器上,那么只需将文本数据传递到服务器,并使用一些服务器端语言执行文件编写代码。 要在客户端存储相当小的信息,可以使用cookie。 使用HTML5 API进行本地存储。

在不可能使用新的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>

上面的答案是有用的,但是,我找到了代码,它可以帮助你直接下载文本文件点击按钮。 在此代码中,您还可以更改文件名,如您所愿。它是纯javascript功能与HTML5。 对我有用!

function saveTextAsFile()
{
    var textToWrite = document.getElementById("inputTextToSave").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
      var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

使用上面用户@useless-code (https://stackoverflow.com/a/21016088/327386)的代码来生成文件。 如果你想自动下载文件,将刚刚生成的textFile传递给这个函数:

var downloadFile = function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
}
const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();

在这里检查Blob文档- Blob MDN为文件类型提供额外的参数。默认情况下,它将生成.txt文件