Convert File to Base 64
by Bret Lowrey
HTML
<script src="https://blueimp.github.io/JavaScript-MD5/js/md5.js"></script>
<form>
<span>
<label for="uploadFile">Convert to Base 64:</label>
<input type="file" id="uploadFile" name="uploadFile" />
</span>
</form>
<div>
<h3>Output</h3>
<textarea id="base64text" name="base64text"></textarea>
<button id="download" onclick="download()">Download
</button>
</div>
CSS
body {
margin: 20px auto;
max-width: 752px;
line-height: 1.6;
font-size: 18px;
color: #444;
padding: 0 10px
}
textarea {
min-width: 95%;
min-height: 300px;
}
JavaScript
const saveAs = (function() {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return (data, fileName) => {
const blob = new Blob([data], {
type: "octet/stream"
});
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
document.getElementById('uploadFile').addEventListener("change",
event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
// 100 kB
if (file.size < 1024 * 100) {
document.getElementById('base64text').value = reader.result;
} else {
saveAs(reader.result, file.name + ".txt");
document.getElementById('base64text').value = "See file";
}
}
}, false);
const dataURLtoBlob = dataurl => {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
window.download = () => {
const dataurl = document.getElementById('base64text').value;
saveAs(dataURLtoBlob(dataurl), md5(dataurl));
};