javascript - Return variable from a reader.onload event -
i reading array via javascript , saving size of array in reader.onload event. think reader.onload function called when file has finished uploading. event.target.result stores array. array saved variable used in other functions but, tried initializing empty array , using
slice function but, didn't work. console returns undefined value.
here code
<!doctype html> <html> <head> <title> home page </title> </head> <body> <input type="file" id="file" name="files[]" multiple/> <output id="list"></output> <p id="demo"></p> <script> function handlefileselect(evt) { // grab file uploaded type file. // evt event triggered // evt.target returns element triggered event // evt.target.files[0] returns file uploaded, type file var file = evt.target.files[0]; var myarray = []; // instantiate filereader object read/save file uploaded var reader = new filereader(); // when load event fired (the file has finished uploading) function called reader.onload = function(event) { // result attribute contains arraybuffer representing file's data. var arraybuffer = event.target.result; myarray = arraybuffer.slice(0); document.getelementbyid("demo").innerhtml = arraybuffer.bytelength; } // read file , save array. once read finished loadend triggered reader.readasarraybuffer(file); console.log(myarray.bytelength); } //console.log(myarray.bytelength); document.getelementbyid('file').addeventlistener('change', handlefileselect, false); </script> </body>
onload happens asynchronously. whatever logic depends on myarray needs happen within onload function.
reader.onload = function(event) { var arraybuffer = event.target.result; var myarray = arraybuffer.slice(0); document.getelementbyid("demo").innerhtml = arraybuffer.bytelength; // needs happen here console.log(myarray.bytelength); } reader.readasarraybuffer(file); this very, similar asked question (regarding ajax/async callbacks) how return value asynchronous callback function?
by way, asynchronous because don't want block entire user interface while waiting potentially long operation of reading file. that's why we're using onload handler here.
Comments
Post a Comment