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

JavascriptHtmlBlob

Javascript Problem Overview


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!"

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

@joey asked how to wrap @philipp's answer in a function, so here's a solution that does that in modern Javascript (thanks @Endless):

const text = await new Response(blob).text()

Solution 3 - Javascript

If the browser supports it, you could go via a blob URI and XMLHttpRequest it

function blobToString(b) {
    var u, x;
    u = URL.createObjectURL(b);
    x = new XMLHttpRequest();
    x.open('GET', u, false); // although sync, you're not fetching over internet
    x.send();
    URL.revokeObjectURL(u);
    return x.responseText;
}

Then

var b = new Blob(['hello world']);
blobToString(b); // "hello world"

Solution 4 - Javascript

You could use the blob.text() method.

blob.text().then(text => {
  let blobText = text
})

It will return the content of the blob in UTF-8 encoding. Note that it has to be in an async.

Solution 5 - Javascript

Try:

var mystring = "Hello World!";
var myblob = new Blob([mystring], {
    type: 'text/plain'
});
mystring = "";
outurl = URL.createObjectURL(myblob);
fetch(outurl)
.then(res => res.text())
.then(data => {
    console.log(data)
})

//'Hello World'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoeyView Question on Stackoverflow
Solution 1 - JavascriptPhilippView Answer on Stackoverflow
Solution 2 - JavascriptkpgView Answer on Stackoverflow
Solution 3 - JavascriptPaul S.View Answer on Stackoverflow
Solution 4 - Javascript21rwView Answer on Stackoverflow
Solution 5 - JavascriptBlaze612 YTView Answer on Stackoverflow