20

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
  • 22,934
  • 9
  • 44
  • 60
Desistreus
  • 251
  • 1
  • 3
  • 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

4 Answers4

23

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
  • 36,864
  • 18
  • 72
  • 104
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');
Augustin Riedinger
  • 18,776
  • 27
  • 114
  • 183
1

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
  • 7,636
  • 2
  • 16
  • 23
-1

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