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