0

I'm trying to upload an image with FileReader() and convert it to base64. This only works when after I upload the image twice, otherwise, a blank canvas/image gets posted instead.

This is my input:

 <input type="file" id="file" class="file"/><canvas id="canvas"></canvas>

This is the FileReader():

        var file = document.querySelector('input[type=file]').files[0];
        var fr = new FileReader();
        fr.onload = createImage;   // onload fires after reading is complete
        fr.readAsDataURL(file);    // begin reading

        function createImage() {
            img = new Image();
            img.onload = imageLoaded;
            img.src = fr.result;
        }

        function imageLoaded() {
            var canvas = document.getElementById("canvas")
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img,0,0);
        }
        var img64 = canvas.toDataURL().split(",")[1];
        var params = {
            "media_data": img64
        };
knights
  • 1
  • 2
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CBroe Mar 28 '17 at 20:04
  • Hey you cant use filereader to convert the svg to base64 and show in img tag it will only work for png,jpg,jpeg these types – Babar Hussain Mar 28 '17 at 20:04
  • You call readAsDataURL immediately after assigning only a _handler function_ for the load event, but the first time this event occurs only later, because the browser does not have the image already cached yet. You need to read the image _inside_ the onload handler function; this is a very similar kind of async behavior to what the duplicate is about, so go check that for further explanation. – CBroe Mar 28 '17 at 20:07
  • @CBroe the problem is that he/she calls `toDataURL` before the onloads events, everything else is fine. To OP, this call should be made at the end of `imageLoaded`. Weird you've got it the second time though since `canvas` should be undefined in that scope. – Kaiido Mar 28 '17 at 23:06

0 Answers0