Is it possible to write data to file using only JavaScript?

后端 未结 10 1312
梦如初夏
梦如初夏 2020-11-21 15:45

I want to Write Data to existing file using JavaScript. I don\'t want to print it on console. I want to Actually Write data to abc.txt. I read many answered que

10条回答
  •  长情又很酷
    2020-11-21 15:57

    If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.

    But if you want to write data, and enable user to download as a file to local. the following code works:

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

    to use it:

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

提交回复
热议问题