Sometimes, you may receive a file URL that you want to convert into a base64 data string. Allow me to demonstrate the code necessary for converting a file URL to base64 using Node.js.
async function convertUrlToBase64(url) {
try {
// Fetch the file
const response = await fetch(url);
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
//return response.statusText;
}
// Read the file as ArrayBuffer
const buffer = await response.arrayBuffer();
// Convert ArrayBuffer to Base64
const base64 = arrayBufferToBase64(buffer);
return base64;
console.log("base data is",base64);
} catch (error) {
console.error('Error plugin', error);
return JSON.stringify(error);
}
}
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return Buffer.from(binary, 'binary').toString('base64');
}
// Usage
const fileUrl = 'https://cbe979c350ab6822f70996af87670e41.cdn.bubble.io/f1695201197519x684510935426170900/fghvj.png';
var basedata= await convertUrlToBase64(fileUrl);
return {
output_data:basedata
}
That's all for this blog. Subscribe for more future updates. Thank you!
Follow me on Twitter.
Checkout My Bubble Plugin Course - Use coupon code "THEBUBBLEGROUP" at checkout for 10% discount.