Readme

File to Data URL

Was built for uploading base64 encoded images to GPT4v

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
export async function fileToDataURL(file) {
// Read the file as an ArrayBuffer
const arrayBuffer = await file.arrayBuffer();
// Convert ArrayBuffer to a typed array (Uint8Array)
const uintArray = new Uint8Array(arrayBuffer);
// Convert typed array to binary string
const binaryString = uintArray.reduce((acc, byte) => acc + String.fromCharCode(byte), "");
// Encode binary string to base64
const base64String = btoa(binaryString);
// Determine the MIME type
const mimeType = file.type || "application/octet-stream";
// Create the Base64 encoded Data URL
return `data:${mimeType};base64,${base64String}`;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
June 17, 2024