26

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
  })
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Desistreus
  • 321
  • 1
  • 4
  • 6
  • Why not use a blob url, or just the original url – Musa Jun 22 '17 at 17:20
  • I'm not using the URL in the src because the images I get are coming from an API that requires an authentication token in the header. – Desistreus Jun 23 '17 at 14:39
  • https://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – cilf Jul 11 '19 at 08:08

3 Answers3

34

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) ;
GetFree
  • 40,278
  • 18
  • 77
  • 104
9

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');
Augustin Riedinger
  • 20,909
  • 29
  • 133
  • 206
2

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');
Sergey Geron
  • 9,098
  • 2
  • 22
  • 29