繁体   English   中英

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

[英]Is it possible to write data to file using only JavaScript?

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

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

未捕获的类型错误:非法构造函数

在铬和

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 将数据写入文件吗?

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

这是一个使用此技术从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);

对此的一些建议——

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

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

尝试

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

如果你想下载二进制数据看这里

更新

2020.06.14 我将 Chrome 升级到 83.0 及更高版本 SO 代码段停止工作(原因:沙盒安全限制) - 但 JSFiddle 版本工作 -在这里

上面的答案很有用,但是我找到了可以帮助您在单击按钮时直接下载文本文件的代码 在此代码中,您还可以根据需要更改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();
}

如果无法使用新的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>

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

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

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

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

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

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

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

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

这是一个单页本地文件版本,可在您需要脚本语言的额外处理功能时使用。

  1. 将下面的代码保存到文本文件
  2. 将文件扩展名从“.txt”更改为“.html”
  3. 右键单击 > 打开方式... > 记事本
  4. 根据需要对文字处理进行编程,然后保存
  5. 双击 html 文件在默认浏览器中打开
  6. 结果会在黑框中预览,点击下载得到结果文本文件

代码:

<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
    // do text manipulation here
    let string1 = 'test\r\n';
    let string2 = 'export.';
    
    // assemble final string
    const finalText = string1 + string2;
    
    // convert to blob
    const data = new Blob([finalText], {type: 'text/plain'});
    
    // create file link
    const link = document.createElement('a');
    link.innerHTML = 'download';
    link.setAttribute('download', 'data.txt');
    link.href = window.URL.createObjectURL(data);
    document.body.appendChild(link);
    
    // preview the output in a paragraph
    const htmlBreak = string => {
        return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
    }
    const preview = document.createElement('p');
    preview.innerHTML = htmlBreak(finalText);
    preview.style.border = "1px solid black";
    document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>

的,可能这里的代码是

 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; })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM