Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
J_Nerd Avatar asked Sep 08 '14 22:09

J_Nerd


People also ask

How do I create a BLOB in HTML?

To construct a Blob from other non-blob objects and data, use the Blob() constructor. To create a blob that contains a subset of another blob's data, use the slice() method. To obtain a Blob object for a file on the user's file system, see the File documentation.

How do I download a BLOB response?

Creating the download link Create an object URL for the blob object. Create an anchor element ( <a></a> ) Set the href attribute of the anchor element to the created object URL. Set the download attribute to the filename of the file to be downloaded.

How do you make a file downloadable in JavaScript?

To receive our files URL, we use URL. createObjectURL() which receives our file object as a parameter. Then, specify the name the saved file should have by default with setting the download attribute of the link. Finally, we mount the link in the DOM, click it artificially, and remove it from the DOM.


1 Answers

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

like image 147
spencer.sm Avatar answered Sep 21 '22 12:09

spencer.sm