Created
March 14, 2018 17:07
-
-
Save bennycode/b7f6c5a0c7e0159c28b01df381155ab3 to your computer and use it in GitHub Desktop.
Image file to Base64 data URI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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