Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

javascript - HTML5 FileReader how to return result?

I use JS FileReader. I want to get result after file reading operation and work with this data. FileReader is asynchronous and I don't know when result is ready. How to get it done right?

$(document).ready(function(){
    $('#file_input').on('change', function(e){
        var res = readFile(this.files[0]);

        //my some manipulate with res

        $('#output_field').text(res);
    });
});

function readFile(file){
    var reader = new FileReader(),
        result = 'empty';

    reader.onload = function(e)
    {
        result = e.target.result;
    };

    reader.readAsText(file);

    //waiting until result is empty?

    return result;
}

http://jsfiddle.net/ub22m/4/

It's show "empty".

How to wait until "result" is empty? Another way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Reading happens asynchronously. You need to provide a custom onload callback that defines what should happen when the read completes:

$(document).ready(function(){
    $('#file_input').on('change', function(e){
        readFile(this.files[0], function(e) {
            // use result in callback...
            $('#output_field').text(e.target.result);
        });
    });
});

function readFile(file, onLoadCallback){
    var reader = new FileReader();
    reader.onload = onLoadCallback;
    reader.readAsText(file);
}

(See the Fiddle.)

Note that readFile does not return a value. ?Instead, it accepts a callback function, which will fire whenever the read is done. The $('#output_field').text operation is moved into the callback function. This ensures that that operation will not run until the reader's onload callback fires, when e.target.result will be filled.

Programming with callbacks is a bit difficult to get right at first, but it is absolutely necessary for implementing advanced functionality.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...