Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!"
like image 804
Joey Avatar asked Apr 12 '14 00:04

Joey


People also ask

How do I recover a blob File?

To restore a soft-deleted blob or directory in the Azure portal, first display the blob or directory's properties, then select the Undelete button on the Overview tab. The following image shows the Undelete button on a soft-deleted directory.

Is blob a string?

A BLOB (binary large object) is a varying-length binary string that can be up to 2,147,483,647 characters long. Like other binary types, BLOB strings are not associated with a code page.

How do I check if a string is a blob?

To check if a variable is a blob in JavaScript, we can use the instanceof operator. to create a blob with: const myBlob = new Blob(['test text'], { type: 'text/plain' });


4 Answers

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);
like image 127
Philipp Avatar answered Oct 17 '22 16:10

Philipp


@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()
like image 22
kpg Avatar answered Oct 17 '22 17:10

kpg


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"
like image 26
Paul S. Avatar answered Oct 17 '22 16:10

Paul S.


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.

like image 12
21rw Avatar answered Oct 17 '22 16:10

21rw