简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM