Variable not fully loaded in javascript

I am trying to convert an image to base64. I wrote 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 warn readerEvt.target.result , it says 131494 characters, but when I load it into a variable, only 10001 characters are loaded. This makes the image incomplete when decoding back with base64. Any help would be appreciated.

+5
source share
1 answer

I tried the same code with the code sample that you tried to do above, and this allowed me to load the local image file into base64 data and fill the image accordingly without errors. Try it...

 <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 still does not work for you, there may be some problems with the image you are trying to upload.

+2
source

All Articles