How to Convert String to Blob

Jul 23, 2021 / Updated on Jul 23, 2021

The simplest way is to use the Blob constructor.

To convert a string to Blob

const str = 'hello world';
const blob = new Blob([str], { type : 'plain/text' });

To convert a JSON to Blob

const obj = { hello: 'world' };
const blob = new Blob([JSON.stringify(obj, null, 2)], { type : 'application/json' });

Another way is use fetch if your content is in base64 encode data

const base64str = "aGVsbG8gd29ybGQ=";
const blob = await fetch(`data:plain/text;base64,${base64str}`).then(res => res.blob());

or as a generic function

// Declare function
const base64ToBlob = async (base64, type = 'application/octet-stream') => 
  fetch(`data:${type};base64,${base64}`)
  .then(res => res.blob())

// Call function
const blob = await base64ToBlob('iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', 'image/png')

Browser Support: https://caniuse.com/?search=fetch

Convert Blob to String

var reader = new FileReader();
reader.onload = function() {
    alert(reader.result);
}
reader.readAsText(blob);

or as a function

async function blobToString (blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = reject;
    reader.onload = () => { resolve(reader.result) };
    reader.readAsDataURL(blob);
  })
}

const base64String = await blobToString(blob);
comments powered by Disqus
Categories:
Tags: