Search code examples
javascriptblob

Javascript convert a Blob object to a string and back


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


Solution

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