Reputation: 35
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 ??
Upvotes: 0
Views: 3108
Reputation: 19301
Here's a simple example converting the first image selected using the file browse button. File reading occurs on the client side after an image has been selected. File reading is asynchronous so I've promisified the file reading function:
"use strict";
const fileDataURL = file => new Promise((resolve,reject) => {
let fr = new FileReader();
fr.onload = () => resolve( fr.result);
fr.onerror = reject;
fr.readAsDataURL( file)
});
function showResult(file) {
fileDataURL( file)
.then( data => (document.getElementById("result").textContent = data))
.catch(err => console.log(err));
}
#result {
width: 80%;
font-family: monospace;
overflow-wrap: break-word;
}
<p>
<input type="file" onchange="showResult( this.files[0]);" accept="image/*">
<div>Data URL:</div>
<div id="result"></div>
Upvotes: 4