Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 FileReader Problems

I am using the Google chrome browser and I run the following code in the console, which seems to work, but when I run it in the script it doesn't

reader = new FileReader();
reader.readAsDataURL($("input[name='image']")[0].files[0]);
alert(reader.result)
somevarname=reader.result

The console show the result as a data url, but in the script javascript won't assign the result to the variable and alert is a blank string. What am I doing wrong?

like image 958
Chris Avatar asked Aug 06 '26 00:08

Chris


1 Answers

The FileReader is asynchronous, so in a script the result is set after

alert(reader.result)
somevarname=reader.result

is executed. You have to use the onload property of the FileReader to get the result.
Example:

var reader = new FileReader();
//This function will execute when the reader is done
reader.onload = function(){alert(this.result);};
reader.readAsDataURL($("input[name='image']")[0].files[0]);

For a good HTML5 File API tutorial, go to HTML5 Rocks.

like image 187
Digital Plane Avatar answered Aug 08 '26 17:08

Digital Plane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!