简体   繁体   中英

HTML5 File API: FileReader object is undefined after an error occured

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

This should be the correct way to do it:

reader.onerror = function(event) {
    console.error("File could not be read: " + event.target.error);
};

Inside .onerror , the this 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:

var _this = this; // _this won't change
this.reader.onerror = function() {
    console.log('An error occurred while reading a file.');
    console.log(_this.reader.error);
}

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