Fetch Image and pass base64 to API

Hi there,

I want to implement an "Upload by Url" functionality for images. User puts URL of an image into a textfield and it gets uploaded to the API.

The API I have as a resource in Retool takes a filename and image content as base64. I got this working easily by using the "{{fileSelector.value['0'].base64Data}}. But that was with the file selector. How can I do this now by just providing a text field?

I was able to fetch the data with a customJS script and return the base64.

  • But how can I access this data in a query?
  • or should I trigger the query from this script? How would I pass the fetched base64 data?
  • Finally, it seems JS adds "data:image/jpeg;base64" before the data, which messes up the API? Its not the same when using the fileSelector.

Lots of questions, hope someone can help...

Best,
Sina

function fetchFileFromUrl(url) {
  return fetch(url)
    .then(response => response.blob())
    .then(blob => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onloadend = () => {
          const base64 = reader.result;
          resolve(base64);
        };
        reader.onerror = reject;
        reader.readAsDataURL(blob);
      });
    });
}

return fetchFileFromUrl(fileUrlInput.value);

Meanwhile I found a solution:

  1. Created a new API resource, which just has a simple parameter GET
  2. Added a query to my app which passes the URL of the form, download the data and then triggers the second API to upload the data. In the second API I can just use "previousqueryname.value".

Less code, probably using more robust Retool functions.

1 Like

Hi @Sina - I'm looking into your topic. Have you already solved it?

P.S. Welcome to the community!

:hugs:

Yes, just did. I think it would be good to cover this topic somewhere in the docs. Loading a remove file into the system is probably happening quite often...

Again, key to the solution was to create a "download" resource, basically a get API without further specifications.

Great @Sina - thanks for sharing!

1 Like

Thank you all for contributing here, and thank you for the callout about this being in our docs, @Sina!

Would something like this be helpful? :slight_smile:

https://docs.retool.com/queries/guides/files#fetch-files-using-a-url

Hi Victoria,

Great start. For "dummies" maybe add a screenshot how to add the query and another with some text how to use the resource and display an image in an app. Then its totally clear.

Thanks!

Sina

Thank you for the note! Just passed it along to our docs team. :pray:

2 Likes