Skip to content

Instantly share code, notes, and snippets.

@FrankSpierings
Created December 9, 2024 16:15
JavaScript file input button to base64
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<input type="file" id="upload" name="filename">
<script>
async function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
// Remove the data URL part if you only want the base64 string.
reader.onloadend = () => resolve(reader.result.split(',')[1]);
reader.onerror = reject;
// Read the Blob as a data URL.
reader.readAsDataURL(blob);
});
}
// Bind to upload button
const upload = document.getElementById("upload");
// Add a change handler
upload.addEventListener("change", (params) => {
// For each added file
Array.from(event.srcElement.files).forEach(async (file) => {
// Create a file blob
console.log(file);
const blob = new Blob([file]);
// Encode the blob to base64
const encoded = await blobToBase64(blob);
// Print the result
console.log(`File: "${file.name}"\n${encoded}`);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment