是否可以仅使用JavaScript将数据写入文件?

par*_*shm 162 html javascript html5

我想使用JavaScript将数据写入现有文件.我不想在控制台上打印它.我想实际写入数据abc.txt.我阅读了许多已回答的问题但是他们在控制台上打印的每一个问 在某些地方,他们已经给了代码,但它不起作用.所以请任何人帮助我如何实际将数据写入文件.

我引用了代码,但它不起作用:给出错误:

 Uncaught TypeError: Illegal constructor 
Run Code Online (Sandbox Code Playgroud)

在铬和

 SecurityError: The operation is insecure.
Run Code Online (Sandbox Code Playgroud)

在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();
}
Run Code Online (Sandbox Code Playgroud)

那么我们是否可以仅使用Javascript或NOT将数据写入文件?请帮助我提前谢谢

Use*_*ode 188

您可以使用Blob和在浏览器中创建文件URL.createObjectURL.所有最新的浏览器支持此.

您无法直接保存您创建的文件,因为这会导致大量安全问题,但您可以将其作为用户的下载链接提供.您可以在支持下载属性的浏览器中通过链接的download属性建议文件名.与任何其他下载一样,下载文件的用户虽然对文件名有最终决定权.

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;
  };
Run Code Online (Sandbox Code Playgroud)

这是一个使用此技术保存任意文本的示例textarea.

如果您想立即启动下载而不是要求用户点击链接,您可以使用鼠标事件模拟链接上的鼠标点击,如Lifecube回答所做的那样.我创建了一个使用此技术的更新示例.

  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);
Run Code Online (Sandbox Code Playgroud)

  • 保存的文档中缺少换行符 (2认同)
  • @ user3241111 不是真的,它应该可以工作。像这样的事情并不是那么不寻常。我见过黑客的做法;-) 在过去,我也只是在链接上的“鼠标悬停”上生成文件,但取决于它正在执行的处理量,这可能效果不佳。 (2认同)

Suj*_*wal 79

对此的一些建议 -

  1. 如果您尝试在客户端计算机上编写文件,则无法以任何跨浏览器方式执行此操作.IE确实有一些方法可以让"受信任的"应用程序使用ActiveX对象来读/写文件.
  2. 如果您尝试将其保存在服务器上,则只需将文本数据传递到服务器,然后使用某种服务器端语言执行文件编写代码.
  3. 要在客户端存储一些相当小的信息,您可以使用cookie.
  4. 使用HTML5 API进行本地存储.

  • HTML5 API的最大值仅为5 MB. (25认同)

Lif*_*ube 41

如果您正在谈论浏览器javascript,出于安全原因,您无法将数据直接写入本地文件.HTML 5新API只允许您读取文件.

但是如果要编写数据,并允许用户将文件作为文件下载到本地.以下代码有效:

    function download(strData, strFileName, strMimeType) {
    var D = document,
        A = arguments,
        a = D.createElement("a"),
        d = A[0],
        n = A[1],
        t = A[2] || "text/plain";

    //build download link:
    a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);


    if (window.MSBlobBuilder) { // IE10
        var bb = new MSBlobBuilder();
        bb.append(strData);
        return navigator.msSaveBlob(bb, strFileName);
    } /* end if(window.MSBlobBuilder) */



    if ('download' in a) { //FF20, CH19
        a.setAttribute("download", n);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            var e = D.createEvent("MouseEvents");
            e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            a.dispatchEvent(e);
            D.body.removeChild(a);
        }, 66);
        return true;
    }; /* end if('download' in a) */



    //do iframe dataURL download: (older W3)
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
}
Run Code Online (Sandbox Code Playgroud)

使用它:

download('the content of the file', 'filename.txt', 'text/plain');

  • 上面的解决方案有点过时了。您可能需要考虑 html 5 javascript 库。https://github.com/eligrey/FileSaver.js/ (3认同)
  • 关于在用户不知情的情况下保存文件的几个问题:这种行为正是设计所避免的。这将打开一个易于使用的安全威胁的潘多拉魔盒。Cookie 用于收集用于营销目的的数据。 (3认同)
  • @Lifecube 使用 FileSaver.js,有没有一种方法可以自动将文本保存到文件中而无需用户交互?谢谢!JS新手;感谢你的所有帮助 (2认同)

Nir*_*raj 21

上面的答案是有用的,但我发现代码可以帮助您直接在按钮点击下载文本文件.在此代码中,您还可以filename根据需要进行更改.它是HTML5的纯javascript函数.适合我!

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`createObjectURL`时需要小心.与JS中的大多数东西不同,当你不再引用它们时,用它创建的对象不会自动被垃圾收集; 它们只是在页面关闭时收集垃圾.由于您没有在此代码中使用`URL.revokeObjectURL()`来释放上次调用所使用的内存,因此存在内存泄漏; 如果用户多次调用`saveTextFile`,他们将继续消耗越来越多的内存,因为你从未发布它. (3认同)
  • 优秀.在Opera上为我工作.除了需要替换未知函数:"destroyClickedElement",语句为"document.body.removeChild(event.target)" (2认同)

Kam*_*ski 8

尝试

let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
Run Code Online (Sandbox Code Playgroud)


lor*_*isi 6

在不太可能使用新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);
Run Code Online (Sandbox Code Playgroud)

$('#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);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>
Run Code Online (Sandbox Code Playgroud)


Ron*_*der 5

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();
Run Code Online (Sandbox Code Playgroud)

在此处查看 Blob 文档 - Blob MDN以提供文件类型的额外参数。默认情况下,它会生成 .txt 文件