How to get data out of FileReader

試著忘記壹切 提交于 2020-01-25 07:26:10

问题


I need a little help with FileReader API. Is there any way how to get data from FileReader outside it. I have a "class" with method, where image is read with FileReader and I want to put image data to the class local variable (as shown in following code).

I do know that FileReader works asynchronously and my solution is wrong. Is there any way how to make it work? Thank you.

CanvasState.prototype.addImage = function(inputFile) {
    var file = inputFile;
    var reader = new FileReader();
    reader.onload = this.loadImageData;
    reader.readAsDataURL(file);
}

CanvasState.prototype.loadImageData = function(e) {
    this.hasImage = true;
    this.imageData = e.target.result;
}

回答1:


Try this:

CanvasState.prototype.addImage = function(inputFile) {
    var file = inputFile, self = this;
    var reader = new FileReader();
    reader.onload = function(e) {
           self.hasImage = true;
            self.imageData = e.target.result;
       };

    reader.readAsDataURL(file);
}



回答2:


This is an issue with the way this is set in a function. When you do:

    foo.bar();

this inside bar() will be foo. But if you do:

    var bar = foo.bar;
    bar();

this will be the global object.

In your case, the problem is that when you set reader.onload, you are setting it to the function pulled out of the CanvasState prototype. When the reader loads and then calls that function, it is like the example above where the this will be the global object, and not the same it was inside addImage.

To fix this, you can use the bind() method to create a new function will call loadImageData with the this you expect.

Basically, change:

...
reader.onload = this.loadImageData;
...

to:

...
reader.onload = this.loadImageData.bind(this);
...

Check out JavaScript Function bind for more info and interactive examples.



来源:https://stackoverflow.com/questions/16177781/how-to-get-data-out-of-filereader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!