JQuery Onload function stopped for loop, passing for loop x inside function

I am transferring image files from XMLHttpRequest for this readfiles (files) function using dataTransfer

what I'm trying to do is preview the images and image file names at the same time and in the same string code inside the reader.onload () function .

and because more than 1 function file will be transferred, I threw them into a loop

The problem is that I am trying to view images using readDataURL , but file names cannot be viewed. I think because the reader.onload () function stopped for a loop from looping through image files.

Here is my code

function readfiles(files) {

    var x;

    for(x = 0; x < files.length; x = x + 1) {

        var reader = new FileReader();
        reader.readAsDataURL(files[x]);
        reader.onload = function(e) {
            console.log(e.target.result);
            console.log(files[x].name);
        }   

    }
}

searched for a solution for about 5 hours, any help!

+4
source share
2 answers

The ROX response is incorrect. In his case, you will see that it will output the same file name 4 times. What you need is a closure that will essentially maintain the correct context at each iteration. You can achieve this as follows. Check out the script http://jsfiddle.net/cy03fc8x/ .

function readfiles(files) {
    for(x = 0; x < files.length; x = x + 1) {
        var file = files[x];
        (function(file){   //this is a closure which we use to ensure each iteration has the right version of the variable 'file'
            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function(e) {
                console.log(e.target.result);
                console.log(file.name);
            }
        })(file);          //on each iteration, pass in the current file to the closure so that it can be used within

    }
}
+4
source

Since it onloadwill be launched later, at this point there xwill be more than your number of files. For example, if you have 4 files, it xwill be 5when executed onload.

:

function readfiles(files) {
    for (var x = 0; x < files.length; x = x + 1) {
        // keep reference to current file on iteration
        var file = files[x];

        // create closure and execute it
        (function (file) {
            var reader = new FileReader();
            reader.readAsDataURL(file);

            reader.onload = function(e) {
                console.log(file.name);
            }
        }(file)); // pass the `file` to the function
    }
}
+1

All Articles