5

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.

angelcool.net
  • 2,505
  • 1
  • 24
  • 26
Amarendra Reddy
  • 243
  • 2
  • 17
  • Have you looked through this: http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript – dYale Apr 29 '16 at 20:18
  • The base64image.length gives me 131494 aprox charecters but when i try to use alert only 10001 is getting loaded. Is there a limitation here? – Amarendra Reddy Apr 29 '16 at 20:24
  • There shouldn't be. I've just ran a test using onload (as well as onloadend) and they both work fine, given a successful load, of course, as onloadend will be called whether successful or not. I tried it on a filesize of over 3.5 Mb and it loaded the data as base64 and populated an image accordingly. – ManoDestra Apr 29 '16 at 20:37

1 Answers1

2

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.

ManoDestra
  • 6,325
  • 6
  • 26
  • 50