简体   繁体   中英

get the result from the FileReader()

I have the following problem.

I have an upload form for multiple files. The upload process goes fine. The problem is related with the FileReader() result. As I am uploading multiple files(images) I need to create corresponding thumbs when the upload is finished.

files = e.target.files;

for (var i = 0; i < files.length; i++) {

    //ajax request goes here

    var reader = new FileReader();
    reader.onload = (function (e) {

        var img = document.createElement('img');
        img.file = e;
        img.className = 'thumbs_';
        img.src = e.target.result;

        //Every image has a wrapper div with the id 'nDv0','nDv1','nDv2' etc.                   

        document.getElementById('nDv' + i).appendChild(img);
    })(e);

    reader.readAsDataURL(files[i]);

    //request sent

}

If I remove the closures around the anonymous function, i's value will be anything when the for loop exits. For example, if there are 3 files, i's value will be 3 and the results will be appended to the last wrapper div and images will be displayed.

With closures every image is getting appended to the corresponding div, but the images won't be displayed as the returned result is undefined.

So, how can I append every thumb to its corresponding div?

You has a logic error :

reader.onload = (function (e) {
    //onload code
    //inside function e is event from outside
})(e);//e is event from upper code

And the i will be equal to files.length because onload handler is async. So you must change your onload handler to:

reader.onload = function (index) {
    var img = document.createElement('img');
    img.className = 'thumbs_';//it's right className?
    img.src = this.result;//result is dataURL                
    document.getElementById('nDv' + index).appendChild(img);
}.bind(reader, i);

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