Javascript - I created a blob from a string, how do I get the string back out?

Joey picture Joey · Apr 12, 2014 · Viewed 84.8k times · Source

I have a string that I called Blob() on:

var mystring = "Hello World!";
var myblob = new Blob([mystring], {
    type: 'text/plain'
});
mystring = "";

How do I get the string back out?

function getBlobData(blob) {
    // Not sure what code to put here
}
alert(getBlobData(myblob)); // should alert "Hello World!"

Answer

Philipp picture Philipp · Apr 12, 2014

In order to extract data from a Blob, you need a FileReader.

var reader = new FileReader();
reader.onload = function() {
    alert(reader.result);
}
reader.readAsText(blob);