I am trying to convert image to base64. I have written the following code:
if (file)
{
var reader = new FileReader();
reader.onload = function(readerEvt)
{
alert(readerEvt.target.result);
var image = readerEvt.target.result;
var base64image = image.split(',')[1];
var key = 'image'+i;
images[key] = image;
//$('#image_preview').attr('src', readerEvt.target.result);
};
reader.readAsDataURL(file);
}
But when i alert the readerEvt.target.result
it says 131494 characters but when i load it to a variable only 10001 characters is loaded. This makes the image incomplete when decoded back from base64. Any help will appreciated.
I tried similar code to the code sample you tried above, and it allowed me to load a local image file into base64 data and populate an image accordingly, without error. Try this...
<input id="txtFile" type="file" onchange="loadFile();">
<br>
<img id="imgTest">
<script>
function loadFile() {
var file = document.getElementById('txtFile').files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
var image = readerEvt.target.result;
var base64image = image.split(',')[1];
console.log(readerEvt.target.result);
document.getElementById('imgTest').src = readerEvt.target.result;
};
reader.readAsDataURL(file);
} else {
console.log('Exception');
}
}
</script>
If it's still not working for you, then there is perhaps some problem with the image you are trying to load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With