简体   繁体   中英

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

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 via a .txt file. How would I go about doing this if it is possible??

HTML:

<input type="button" onclick="newBlob()" value="Clear and Export">

Javascript:

function newBlob() {
    var blobData = document.getElementById("ticketlog").value;
    var myBlob = new Blob(blobData, "plain/text");
    blobURL = URL.createObjectURL(myBlob);
    var href = document.createElement("a");
    href.href = blobURL;
    href.download = myBlob;
    href.id = "download"
    document.getElementById("download").click();
}

I figure if I make the Blob, create a URL for it, map the URL to an "a" element then auto-click it then it should work in theory. Obviously I'm missing something though. Any help would be fantastic. 1st question on this site btw:p

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

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) .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM