I’m struggling to send a file from Google Drive to the OpenAI API for chat completion. I’ve got the authentication part down and can access the file, but I’m hitting a wall when trying to convert the Blob to a base64 string.
Here’s what I’ve tried:
const fileData = await driveApi.files.get({
fileId: 'some_file_id',
alt: 'media',
});
const fileBlob = fileData.data;
const bufferArray = await fileBlob.arrayBuffer();
const byteArray = new Uint8Array(bufferArray);
// First attempt
const stringFromChars = String.fromCharCode(...byteArray);
const encodedString = btoa(stringFromChars);
// Second attempt
const decodedText = new TextDecoder().decode(byteArray);
const encodedString = btoa(decodedText);
Both attempts are failing with either a RangeError or a DOMException. I’m using a Supabase Edge Function for this.
Is there a better way to handle this conversion? Or am I missing something obvious? Any help would be awesome!
hey there! have you tried using the Buffer.from() method? it’s pretty handy for this kinda stuff. here’s a quick example:
const fileData = await driveApi.files.get({
fileId: 'your_file_id',
alt: 'media',
});
const base64 = Buffer.from(fileData.data).toString('base64');
this should work for most file types. good luck with your project!
I’ve faced this exact problem before, and it can be tricky. What worked for me was using the ‘utf8’ encoding when converting the file data. Here’s the approach I took:
const fileData = await driveApi.files.get({
fileId: 'some_file_id',
alt: 'media',
});
const buffer = Buffer.from(await fileData.data.arrayBuffer());
const base64String = buffer.toString('base64');
This method should handle most file types without throwing errors. Just make sure your file isn’t too large, as there are size limits when working with base64 strings. Also, depending on your Supabase Edge Function setup, you might need to adjust the buffer handling.
If you’re still running into issues, it might be worth checking if the file is actually readable or if there are any permission problems with accessing it from Google Drive. Good luck!
I’ve encountered similar issues when working with Google Drive files and the OpenAI API. One approach that worked for me was using the ‘base64’ encoding option directly when retrieving the file from Google Drive. Try modifying your code like this:
const fileData = await driveApi.files.get({
fileId: 'some_file_id',
alt: 'media',
responseType: 'arraybuffer'
});
const base64Data = Buffer.from(fileData.data).toString('base64');
This method avoids the need for manual conversion and should give you the base64 string directly. Make sure you have the necessary permissions to access the file content. If you’re still facing issues, double-check the file type and size, as some files might require additional handling.