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