trafalgarx trafalgarx - 1 year ago 213
Javascript Question

HTML5 FileReader how to return result?

I use JS FileReader and me need take result after file read operation and manipulate with this data. FileReader is read asynchronously and i don't know, when result is ready to use. How to do this?

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

//my some manipulate with res


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

reader.onload = function(e)
result =;


//waiting until result is empty?

return result;

It's show "empty".

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

Answer Source

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

    $('#file_input').on('change', function(e){
        readFile(this.files[0], function(e) {
            // use result in callback...

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

(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 will be filled.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download