开发者

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开发者_StackOverflow中文版[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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜