Base64 File Encoding using Javascript

Posted in software by Christopher R. Wirz on Sun Mar 13 2016

Base64 URIs generally take the form of data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA... which follows the pattern data:[<mime type>][;charset=<charset>][;base64],<encoded data> . The encoded data is often provided by APIs, conversion tools, and designers. It can also be provided directly through the javascript FileReader object.


function getbase64(element) {
	if (element == null){return;}
	if (typeof(element.files) == "undefined"){return;}
	if (element.files.length < 1) {return;}
	var file = element.files[0];
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function () {
		// Do some thing with the result
		document.getElementById("base64content").innerText = reader.result;
	};
}

Easy enough... Let's try it with a file.