'Requesting blob images and transforming to base64 with fetch API

I have some images that will be displayed in a React app. I perform a GET request to a server, which returns images in BLOB format. Then I transform these images to base64. Finally, i'm setting these base64 strings inside the src attribute of an image tag.

Recently I've started using the Fetch API. I was wondering if there is a way to do the transforming in 'one' go.

Below an example to explain my idea so far and/or if this is even possible with the Fetch API. I haven't found anything online yet.

  let reader = new window.FileReader();
  fetch('http://localhost:3000/whatever')
  .then(response => response.blob())
  .then(myBlob => reader.readAsDataURL(myBlob))
  .then(myBase64 => {
    imagesString = myBase64
  }).catch(error => {
    //Lalala
  })


Solution 1:[1]

The return of FileReader.readAsDataURL is not a promise. You have to do it the old way.

fetch('http://localhost:3000/whatever')
.then( response => response.blob() )
.then( blob =>{
    var reader = new FileReader() ;
    reader.onload = function(){ console.log(this.result) } ; // <--- `this.result` contains a base64 data URI
    reader.readAsDataURL(blob) ;
}) ;

General purpose function:

function urlContentToDataUri(url){
    return  fetch(url)
            .then( response => response.blob() )
            .then( blob => new Promise( callback =>{
                let reader = new FileReader() ;
                reader.onload = function(){ callback(this.result) } ;
                reader.readAsDataURL(blob) ;
            }) ) ;
}

//Usage example:
urlContentToDataUri('http://example.com').then( dataUri => console.log(dataUri) ) ;

//Usage example using await:
let dataUri = await urlContentToDataUri('http://example.com') ;
console.log(dataUri) ;

Solution 2:[2]

Thanks to @GetFree, here's the async/await version of it, with promise error handling:

const imageUrlToBase64 = async url => {
  const response = await fetch(url);
  const blob = await response.blob();
  return new Promise((onSuccess, onError) => {
    try {
      const reader = new FileReader() ;
      reader.onload = function(){ onSuccess(this.result) } ;
      reader.readAsDataURL(blob) ;
    } catch(e) {
      onError(e);
    }
  });
};

Usage:

const base64 = await imageUrlToBase64('https://via.placeholder.com/150');

Solution 3:[3]

If somebody gonna need to do it in Node.js:

const fetch = require('cross-fetch');
const response  = await fetch(url);
const base64_body = (await response.buffer()).toString('base64');

Solution 4:[4]

I do it as below:

const response  = await fetch(myRequest);
if (!response.ok) {
  //TODO: notify something
} else {
  // read all response
  const rawcontent = await response.arrayBuffer();
  // convert to base64. convertToBase64() function could be copied from this URL: https://docs.microsoft.com/en-us/office/dev/scripts/resources/samples/add-image-to-workbook
  const Base64Data = convertToBase64(rawcontent);
  //TODO: do something with the base64 data
  console.log(Base64Data .toString());
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Augustin Riedinger
Solution 3 Sergey Geron
Solution 4 Nguyen Duc Tien