6

I am currently working on a Unity Webgl project and I am new to javascript and web .

In my project the user have to be able to add pictures and videos to the the webgl player, picture works fine (thanks to gman's code on this thread). I use it as a base for my script. Of course I have changed the input accept to be able to get video (mp4 only). But I am getting some trouble.

I have read this tutorial and all the doc I have found about javascript File, Blob, etc. But I didn't make it work. I believe there is something I don't understand with FileReader since the console.log on the "load" listener is never called, same for the "onerror" listener except when I click on cancel (from the code here).

function getPic( evt ) {
    var file = document.querySelector( 'input[type=file]' ).files[0];
    var reader = new FileReader();

    reader.addEventListener( "onload", function () {
        reader.readAsDataURL( file );
        console.log( reader.result );
    }, false );
    reader.addEventListener( "onerror", function ( error ) {
        console.log( "error" + error );
    }, false );
}

I have tried onloadend too but it don't work, since the onload/onloadend listener is never called my script print "null". Is that a good beginning or is there a simpler way to get video/image from user computer ?

Rajib Chy
  • 800
  • 10
  • 22
hal9000
  • 83
  • 1
  • 1
  • 6
  • You may read more about FileReader Api from here https://developer.mozilla.org/en-US/docs/Web/API/FileReader – Rajib Chy Jul 14 '19 at 22:16

1 Answers1

4

FileReader.onload property contains a event handler executed when the 'load' event is fired, when content read (eg. readAsDataURL) is available

  • the event listener should be listening for the 'load' event instead of 'onload'

reader.addEventListener("load", function(event) {...
reader.onload = function() {...

reader.readAsDataURL(file) is being called inside the callback function

  • move the line reader.readAsDataURL(file); outside the 'load' event callback function

reader.addEventListener("load", function(){
   console.log(reader.result);
}, false);

reader.readAsDataURL(file);

https://jsfiddle.net/3vk4u0fr/

bfmags
  • 2,885
  • 2
  • 17
  • 28
  • Thanks for the quick response ! I have tried it but it never go on the onload listener. – hal9000 May 30 '16 at 15:30
  • I have no console error, the filename is correct and I go through all the function without passing by onload. – hal9000 May 30 '16 at 15:39
  • 1
    It works great ! (reader.onload = function() ...) So I believe that I just have to ReadAsDataURL and use this.result. I will check that ! – hal9000 May 30 '16 at 16:10