Javascript convert a Blob object to a string and back
Asked Answered
S

2

11

I have to send a Blob as a String and convert it back to an Blob. The method blob.text() returns a promise with it's content as a String. But how can i convert this string back to a blob? I want to convert it into an image data url.

https://developer.mozilla.org/en-US/docs/Web/API/Blob

Sheaff answered 6/7, 2021 at 19:21 Comment(0)
R
25

To convert a string to a blob, you use the new Blob interface:

const blob = new Blob([string], {
  type: 'image/jpeg' // or whatever your Content-Type is
});

See this section of the document you linked to.

If you have a Blob object called blob, blob.type will give its content type. So you could deconstruct and reconstruct it as follows:

const string = await blob.text();
const type = blob.type;
const blob2 = new Blob([string], {type: type});
Reaganreagen answered 6/7, 2021 at 19:53 Comment(2)
Excellent! Way simpler than using FileReader, as suggested by most google results.Sanctify
Doesn't seem to work for images in chrome.Ultravirus
I
1
const base64Data = "dGVRAXXRoZXIUl";

Depending on the format of the base64 string, you might need to prepend content type data. For example, a JPEG image

const base64Return = await fetch(`data:image/jpeg;base64,${base64Data}`);

Then, convert the response to a blob

const blob = await base64Return.blob();

For "text/html" format, for example, you can get the raw text

const text = await base64Return.text();
Impinge answered 6/7, 2021 at 19:33 Comment(2)
fetch argument should be quoted - fetch("data:image/jpeg;base64,${base64Data}")Agalloch
should i use the return value of blob.text() as base64Data?Sheaff

© 2022 - 2024 — McMap. All rights reserved.