Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileReader API 'load' event

Tags:

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 ?

like image 537
hal9000 Avatar asked May 30 '16 15:05

hal9000


1 Answers

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/

like image 194
bfmags Avatar answered Oct 11 '22 10:10

bfmags