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

 风华绝代LL58 发布于 2023-02-04 23:50

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

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

 Uncaught TypeError: Illegal constructor 

在铬和

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

6 个回答
  • 您可以使用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;
      };
    

    这是一个使用此技术保存任意文本的示例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);
    

    2023-02-04 23:58 回答
  • 尝试

    let a = document.createElement('a');
    a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
    a.download = 'abc.txt';
    a.click();
    2023-02-05 00:05 回答
  • 上面的答案是有用的,但我发现代码可以帮助您直接在按钮点击下载文本文件.在此代码中,您还可以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();
    }
    

    2023-02-05 00:07 回答
  • 对此的一些建议 -

      如果您尝试在客户端计算机上编写文件,则无法以任何跨浏览器方式执行此操作.IE确实有一些方法可以让"受信任的"应用程序使用ActiveX对象来读/写文件.

      如果您尝试将其保存在服务器上,则只需将文本数据传递到服务器,然后使用某种服务器端语言执行文件编写代码.

      要在客户端存储一些相当小的信息,您可以使用cookie.

      使用HTML5 API进行本地存储.

    2023-02-05 00:07 回答
  • 在不太可能使用新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>
    2023-02-05 00:11 回答
  • 如果您正在谈论浏览器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');

    2023-02-05 00:13 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有