How to Convert all Images to Base64 and Update Records in Retool

Hello everyone,

I am currently working on an application in Retool where I need to convert stored images to base64 and update the records in my database. Here are the details of my setup and what I have tried so far:
. Context:

  • I have a table DB2_Table_Batisses that contains columns for image codes (e.g., annexe1_photo, annexe2_photo, etc.).
  • I want to convert these codes to base64 URLs and store them in corresponding columns (Annexe1_base64, Annexe2_base64, etc.).
const myImageUrl = 'https://i.pinimg.com/736x/ba/92/7f/ba927ff34cd961ce2c184d47e8ead9f6.jpg";

/**
 * Fetches an image from URL and encodes it into a base64 string
 * Adapted from this thread: https://community.cloudflare.com/t/convert-request-body-to-base64-encoded-string-solved/99341/5
 * @param {string} url
 * @returns {Promise<string>}
 */
async function imageUrlToBase64(url) {
  let string = "";
  const response = await fetch(url);
  const buffer = await response.arrayBuffer();
  (new Uint8Array(buffer)).forEach(
    (byte) => { string += String.fromCharCode(byte) }
  )
  return btoa(string);
}

// usage:
const imageBase64_async = await imageUrlToBase64(myImageUrl);

// usage without await
imageUrlToBase64(myImageUrl).then((ret) => {
  console.log("Base64String: ", ret);
});

source

you could also use fetch with FileReader

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 myImageUrl = 'https://i.pinimg.com/736x/ba/92/7f/ba927ff34cd961ce2c184d47e8ead9f6.jpg";
const base64 = await imageUrlToBase64(myImageUrl);
1 Like