admin管理员组

文章数量:1323335

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?

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?

Share Improve this question edited May 29, 2012 at 17:13 Kijewski 26k14 gold badges107 silver badges147 bronze badges asked Jul 22, 2011 at 15:08 ChrisChris 5,0739 gold badges40 silver badges58 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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.

本文标签: javascriptHTML5 FileReader ProblemsStack Overflow