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!

2 Likes

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

2 Likes