Creating Javascript Blob() with data from HTML Element. Then downloading it as a text file

后端 未结 3 2156
醉酒成梦
醉酒成梦 2020-12-20 16:11

I\'m using an HTML5 site to create a log per-say within a textarea element. I need to pull the data from that area with the click of a button, and download it to my computer

相关标签:
3条回答
  • 2020-12-20 16:48
    const downloadBlobAsFile = (function closure_shell() {
        const a = document.createElement("a");
        return function downloadBlobAsFile(blob, filename) {
            const object_URL = URL.createObjectURL(blob);
            a.href = object_URL;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(object_URL);
        };
    })();
    
    
    document.getElementById("theButton").addEventListener("click", _ => {
        downloadBlobAsFile(new Blob(
            [document.getElementById("ticketlog").value],
            {type: "text/plain"}
        ), "result.txt");
    });
    

    The value of a download property of an <a> element is the name of the file to download, and the constructor of Blob is Blob(array, options).

    0 讨论(0)
  • 2020-12-20 17:01

    The simplest way I've come up with is as follows:

    function download(text, filename){
      var blob = new Blob([text], {type: "text/plain"});
      var url = window.URL.createObjectURL(blob);
      var a = document.createElement("a");
      a.href = url;
      a.download = filename;
      a.click();
    }
    
    download("this is the file", "text.txt");
    

    List of possible blob filestypes: http://www.freeformatter.com/mime-types-list.html

    0 讨论(0)
  • 2020-12-20 17:02

    I used this approach that doesn't involve creating an element and revokes the textFile after the browser showed the text file

    var text = 'hello blob';
    var blob = new Blob([text], { type: 'text/plain' });
    let textFile = window.URL.createObjectURL(blob);
    let window2 = window.open(textFile, 'log.' + new Date() + '.txt');
    window2.onload = e => window.URL.revokeObjectURL(textFile);
    
    0 讨论(0)
提交回复
热议问题