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

5

112

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!"
Geary answered 12/4, 2014 at 0:2 Comment(0)
F
91

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);
Fated answered 12/4, 2014 at 0:8 Comment(5)
So how can I wrap that in a function and have it return the result?Geary
@Geary see question Call An Asynchronous Javascript Function SynchronouslyFated
Well, I got it to wrap in a function. But for some reason it only works the second time I try to access it: jsfiddle.net/vMrF5Geary
@Geary That's because of a race conditions. The asynchronous loading happens in the background. The first time it's not loaded yet, the second time it might already be. However, do not rely on that! That's undefined behavior which will vary from execution to execution. You have absolutely no way to tell how long loading will take.Fated
In case someone else wants to wrap this in a function, see my answer below.Theotokos
T
45

@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()
Theotokos answered 10/1, 2019 at 15:41 Comment(1)
if you want it as a promise just do const text = await new Repsponse(blob).text()Whoopee
L
28

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"
Lanlana answered 12/4, 2014 at 0:24 Comment(3)
it's a bit hacky, isn't there a less hacky way to do it?Bergamo
This works, but chrome 76 now warns of deprecation [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.Tradition
Yes it's working with error in FireFox '85.0.2 (64-bit)' XML Parsing Error: not well-formed Location: blob:http://localhost:4200/40be6ace-691c-43a2-b208-824a0d0a933 Line Number 1, Column 1 for my 'Angular 6' app. To solve this need to add type, const b = new Blob(['hello world'], { type: 'text/plain' });Squid
H
24

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.

Hartfield answered 20/6, 2021 at 23:34 Comment(0)
E
9

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'
Enwrap answered 27/4, 2021 at 16:58 Comment(2)
Haven't tried this, but seems legit according to developer.mozilla.org/de/docs/Web/API/Body/blob and is more straight than the XMLHttpRequest answer of Paul S.Leftwich
Thanks. (I am very new and have not even gotten an upvote until now)Enwrap

© 2022 - 2024 — McMap. All rights reserved.