Skip to content

Instantly share code, notes, and snippets.

@bennycode
Created March 14, 2018 17:07
Show Gist options
  • Save bennycode/b7f6c5a0c7e0159c28b01df381155ab3 to your computer and use it in GitHub Desktop.
Save bennycode/b7f6c5a0c7e0159c28b01df381155ab3 to your computer and use it in GitHub Desktop.
Image file to Base64 data URI
<html>
<head></head>
<body>
<input id="file-upload" multiple="multiple" type="file"/>
<img id="file-placeholder"/>
<script>
function blobToDataURI(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', function () {
resolve(this.result);
}, false);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
document.getElementById('file-upload').addEventListener('change', async function () {
for (const file of this.files) {
console.log(`"${file.name} (${file.type}, ${file.size} bytes)`);
const dataURI = await blobToDataURI(file);
document.getElementById('file-placeholder')
.setAttribute(
'src', dataURI
);
}
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment