Tip: Upload base64 encoded file to Xano

Hi,

I had the need to send a base64 encoded file directly to my Xano endpoint and had some painful iterations with the javascript code snippet.

Now it works perfectly and I wanted to share the script, if there a more people who need to base64 encode things in WeWeb.

Have to say I am not a Coder thus copied things together, so sorry if the code is not beautifully perfect. But it works :wink:

Here we go, hope it helps:

console.log("------ START BASE64 FILEUPLOAD JS -----");

var formData = new FormData();

// Get a reference to the file input
var fileInput = document.querySelector('#file-uploader input');

// Get a reference to the file
const file = fileInput.files[0];
console.log("File: " + file);

// Listen for the result of base64 encoded image 
function boo() {
 return new Promise(function(resolve, reject) {
     
   // Encode the file using the FileReader API
  const reader = new FileReader();
   
   reader.onloadend = () => {
     //optional: If necessary, remove the data tag in the base64 string (depends on how you process the base64 string later)
     var imageData = reader.result.replace("data:", "").replace(/^.+,/, "");
     
     //get content type of file
     var contentType = reader.result.replace("data:", "").match(/^.+;/)[0].replace(";", "");

     console.log(contentType);

     //Add base64 string and contenttype to formData
     formData.append("imageData", imageData);
     formData.append("contentType", contentType);
     
     
     resolve();   
   };
   
   reader.readAsDataURL(file);
   
 });
}

//wait for base64 encoding result
await boo();

//Call Xano endpoint and transmit formdata incl base64 string
//Put your own xanoAuth variable and endpoint URL here
var result = axios.post("https://x8j  .... xano.io/api:49 ... 6/process/scan", formData,{
            headers:{
                "Authorization": "Bearer " + pluginVariables[/* xanoAuth accessToken */ 'f585....4e1']['accessToken'],
                "Content-Type": "multipart/form-data"
    }  
  })    
  
  //wait for Xano response
 var response = await result;
 console.log("response: " + response);

//return result from Xano
 return response;

3 Likes

Used the code from @caffeinatedwes as a base, thanks for that!

3 Likes

Ooooh thanks so much for sharing this @Soenke! Really appreciate it :hugs:

2 Likes

Hello :wave:

For future readers of this post, you can now upload files directly to Xano without writing code with the Encode file as Base64 workflow action.

Here’s the video tutorial we made on the topic:

1 Like

That’s great!!

1 Like

@Joyce Do you know how this would work on a file that’s already part of a Collection list?

e.g. I have a Collection that is a list of files. For each file item, I want to send it as an email, which requires me to encode the file as Base64.

On the button to email the file, I have the workflow below.

However, when I test that, I get the following error:

Uncaught (in promise) TypeError: Failed to execute ‘readAsDataURL’ on ‘FileReader’: parameter 1 is not of type ‘Blob’.
at r (index.8ad6d39a.js:1270:34149)
at new Promise ()
at xt (index.8ad6d39a.js:1270:34039)
at Proxy.runTest (index.8ad6d39a.js:1388:238844)
at index.8ad6d39a.js:1388:222692
at chunk-vendors.c5b4dd71.js:1:107458
at a (chunk-vendors.c5b4dd71.js:1:33337)
at l (chunk-vendors.c5b4dd71.js:1:33420)
at HTMLButtonElement.i (chunk-vendors.c5b4dd71.js:1:94414)
at HTMLButtonElement.sentryWrapped (helpers.ts:98:1)

Do you know what this could be?

It’s not really a file, what you have here is an object describing a file

I suppose we need another action named Get file from URL, so you can use the result inside the Encode file as Base64 action :thinking:

For now you will need a javascript action before your Encode file.

const res = await fetch(item.data.url);
if (!res.ok) {
    throw new Error('File cannot be fetch');
}
return await res.blob();

Then you can use the result of this action and bind it inside your encode file action.

2 Likes

Hello,
I followed all the instructions as per Joyce video, but I’m getting this error when I try to encode the file. Any idea on how to resolve it? Attaching a screenshot of the workflow so far.

name: “TypeError”

stack: “TypeError: Failed to execute ‘readAsDataURL’ on ‘FileReader’: parameter 1 is not of type ‘Blob’. at d (https://editor-cdn.weweb.io/public/js/index.ec272cc6.js:1183:43706) at new Promise () at wt (https://editor-cdn.weweb.io/public/js/index.ec272cc6.js:1183:43596) at Proxy.runTest (https://editor-cdn.weweb.io/public/js/index.ec272cc6.js:1301:247241) at https://editor-cdn.weweb.io/public/js/index.ec272cc6.js:1301:230434 at i..i. (https://editor-cdn.weweb.io/public/js/chunk-vendors.dd416290.js:16:8624) at l (https://editor-cdn.weweb.io/public/js/chunk-vendors.dd416290.js:6:14997) at u (https://editor-cdn.weweb.io/public/js/chunk-vendors.dd416290.js:6:15072) at HTMLButtonElement.i (https://editor-cdn.weweb.io/public/js/chunk-vendors.dd416290.js:14:8312)”

message: “Failed to execute ‘readAsDataURL’ on ‘FileReader’: parameter 1 is not of type ‘Blob’.”

Thank you!

FYI … files can be uploaded from WeWeb to Xano without Base64-encoding the file.

I did this by setting the Xano Request POST Content Type to “multipart/form-data”.

The issue for me with Base64 files were:

  1. Base64 encoding doesn’t pass the file name, so I would need another API parameter to send the file name. This wasn’t ideal because my API is used by other frontends that don’t pass this information and there was no other way to get the file name.
  2. I didn’t want Xano storing files with names like “file-123456a.jpg” because the user cannot recognize if they uploaded the correct file, especially when dealing with documents where metadata is included within the file name itself (e.g., date, invoice #, account #, etc.).
  3. Theoretically, a Base64 encoded file is larger than an unencoded one. The increased size is negligible, but if it matters to you, then don’t Base64 encode it.