Looping through files for FileReader, output always contains last value from loop

后端 未结 6 1464
花落未央
花落未央 2020-11-30 20:04

I\'m using FileReader API to read files on local.



        
6条回答
  •  野性不改
    2020-11-30 20:22

    The problem is you're running the loop now but the callbacks you are setting are getting run later (when the events fire). By the time they run, the loop is over and remains at whatever the last value was. So it will always show "file2" in your case for the name.

    The solution is to put the file name inside a closure with the rest. One way to do this is create an immediately-invoked function expression (IIFE) and pass the file in as a parameter to that function:

    for (var i = 0; i < files.length; i++) { //for multiple files          
        (function(file) {
            var name = file.name;
            var reader = new FileReader();  
            reader.onload = function(e) {  
                // get file content  
                var text = e.target.result; 
                var li = document.createElement("li");
                li.innerHTML = name + "____" + text;
                ul.appendChild(li);
            }
            reader.readAsText(file, "UTF-8");
        })(files[i]);
    }
    

    Alternately, you can define a named function and call it as normal:

    function setupReader(file) {
        var name = file.name;
        var reader = new FileReader();  
        reader.onload = function(e) {  
            // get file content  
            var text = e.target.result; 
            var li = document.createElement("li");
            li.innerHTML = name + "____" + text;
            ul.appendChild(li);
        }
        reader.readAsText(file, "UTF-8");
    }
    
    for (var i = 0; i < files.length; i++) {
        setupReader(files[i]);
    }
    

提交回复
热议问题