HTML5 文件 API:发生错误后 FileReader 对象未定义
我在 Mac OS X 上使用 Chrome 12,并且在文档中包含了 jQuery 1.6.1。
我尝试使用以下代码读取文件,读取文件时发生错误,因此调用 this.error.onerror() ,但 FileReader-Object this.reader 不再存在,我不能得到错误。我也不确定为什么会发生错误,这是我想阅读的常规文本文档。
function FileHandler(files, action) {
console.log('FileHandler called.');
this.files = files;
this.reader = new FileReader();
this.action = action;
this.handle = function() {
console.log('FileHandler.handle called.');
for (var i = 0; i < this.files.length; i++) {
this.reader.readAsDataURL(files[i]);
}
}
this.upload = function() {
console.log('FileHandler.upload called.');
console.log(this.reader);
data = {
content: this.reader.result
}
console.log(data);
}
this.error = function() {
console.log('An error occurred while reading a file.');
console.log(this.reader.error);
}
this.reader.onload = this.upload;
this.reader.onerror = this.error;
}
此代码创建以下控制台输出: http://cl.ly/0j1m3j0o3s071Y1K3A25
I use Chrome 12 on Mac OS X and I've included jQuery 1.6.1 within the document.
I try to read a File with the following code, an error seams to occur while reading the file, so this.error.onerror() is called, but the FileReader-Object this.reader doesn't exists anymore and I can't get the error. I'm also not sure why the error occurs, it's a regular text document I want to read.
function FileHandler(files, action) {
console.log('FileHandler called.');
this.files = files;
this.reader = new FileReader();
this.action = action;
this.handle = function() {
console.log('FileHandler.handle called.');
for (var i = 0; i < this.files.length; i++) {
this.reader.readAsDataURL(files[i]);
}
}
this.upload = function() {
console.log('FileHandler.upload called.');
console.log(this.reader);
data = {
content: this.reader.result
}
console.log(data);
}
this.error = function() {
console.log('An error occurred while reading a file.');
console.log(this.reader.error);
}
this.reader.onload = this.upload;
this.reader.onerror = this.error;
}
This code creates the following console output:
http://cl.ly/0j1m3j0o3s071Y1K3A25
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在
.onerror
内部,this
与外部不同,因为它是一个新函数(具有新作用域)。通过如下静态设置来跟踪
this
:Inside
.onerror
, thethis
is not the same as outside because it's a new function (with a new scope).Keep track of the
this
by setting it statically like this:这应该是正确的方法:
This should be the correct way to do it: