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


当前回答

Try

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 snippet停止工作(原因:沙箱安全限制)-但JSFiddle版本工作-在这里

其他回答

对此,我有一些建议

如果你试图在客户端机器上写一个文件,你不能在任何跨浏览器的方式这样做。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>

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

Try

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 snippet停止工作(原因:沙箱安全限制)-但JSFiddle版本工作-在这里

如果你谈论的是浏览器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;
}

使用它:

下载('文件的内容','filename.txt', 'text/plain');