Public
Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export async function fileToDataURL(file: File) {
const base64String = await fileToBase64(file);
// Determine the MIME type
const mimeType = file.type || "application/octet-stream";
// Create the Base64 encoded Data URL
return `data:${mimeType};base64,${base64String}`;
}
export async function fileToBase64(file: 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
return btoa(binaryString);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
August 27, 2024
@stevekrouse While you can definitely do it manually there is a standard and ostensibly quicker way of converting
File
/Blob
instance to dataURL: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURLTo save you from the
FileReader
setup boilerplate I've createdconvertBlobToDataURL
helper. You can see it in action here: https://www.val.town/v/vladimyr/dataURL_exampleVery cool! Thank you!! I was looking for that