I trying to take image as a file input from the user and the display it as a base64 encoded string. Here's my code
<!DOCTYPE html>
<html>
<head>
<title>JavaScript – Convert Image to Base64 String</title>
</head>
<body>
<input type="file" name="upload" id="file" accept="image/*">
<br>
<br>
<button type="button" onclick="showResult()">Show Source</button>
<div id="image-source">Image Source :</div>
<br>
<div>Data URL:</div>
<div id="result"></div>
<script type="text/javascript">
function toDataURL(src, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
callback(fileReader.result);
}
fileReader.readAsDataURL(xhttp.response);
};
xhttp.responseType = 'blob';
xhttp.open('GET', src, true);
xhttp.send();
}
showResult(){
var x = document.getElementById("file").value;
document.getElementById("image-source").innerHTML = x;
toDataURL(x, function(dataURL) {
// do something with dataURL
document.getElementById('result').innerHTML = dataURL;
});
}
</script>
</body>
</html>
Do I need to store the source of the image seperately to encode it ? Is there a simpler way to encode a user uploaded image ??