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

时间:2014-01-09 05:54:55

标签: javascript html html5

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

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

 Uncaught TypeError: Illegal constructor 

on chrome和

 SecurityError: The operation is insecure.

on 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或NOT将数据写入文件? 请帮我 提前致谢

10 个答案:

答案 0 :(得分:177)

您可以使用BlobURL.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;
  };

这是exampleLifecube使用此技术保存textarea中的任意文字。

如果您想立即启动下载而不是要求用户点击链接,您可以使用鼠标事件模拟链接上的鼠标点击answer {{3}做了。我创建了一个使用此技术的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);

答案 1 :(得分:73)

对此有一些建议 -

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

答案 2 :(得分:38)

如果您正在谈论浏览器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;
}

使用它:

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

答案 3 :(得分:20)

上面的回答非常有用,I found code可以帮助您直接点击按钮下载文本文件。        在此代码中,您还可以根据需要更改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();
}

答案 4 :(得分:5)

如果不能使用新的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>

答案 5 :(得分:3)

使用上面用户@ 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;
}

答案 6 :(得分:2)

我在这里找到了很好的答案,但也找到了一种更简单的方法。

用于创建Blob的按钮和下载链接可以组合在一个链接中,因为链接元素可以具有onclick属性。 (相反,似乎不可能,向按钮添加href无效。)

您可以使用bootstrap将链接样式化为按钮,除了样式外,它仍然是纯JavaScript。

将按钮和下载链接结合在一起还可以减少代码,因为需要的这些丑陋getElementById调用较少。

此示例只需单击一个按钮即可创建文本框并下载:

<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>

答案 7 :(得分:2)

尝试

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

答案 8 :(得分:1)

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文件

答案 9 :(得分:-1)

这里的代码是

const fs = require('fs') 
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 

相关问题