Pass a parameter to FileReader onload event

前端 未结 2 564

I need to read some csv files, given by the user. Files are passed to the page/script using a drag and drop div, that handles the file drop as follows:

funct         


        
相关标签:
2条回答
  • 2020-12-14 08:36

    Try the following:

    var reader = new FileReader();
    reader.onload = (function(theFile){
        var fileName = theFile.name;
        return function(e){
            console.log(fileName);
            console.log(e.target.result);
        };
    })(currFile);   
    reader.readAsText(currFile);
    

    Here, you're creating a new fileName variable each time a file is passed to the outer method. You're then creating a function which has access that variable (due to the closure) and returning it.

    0 讨论(0)
  • 2020-12-14 08:41

    Use Blob API

    Using the new File / Blob API it can be done much easier.

    Your second code block - also solving your problem - could be rewritten as:

    for (let file of files){
     (new Blob([file])).text().then(x=>console.log(file.name,x));
    }
    

    The Blob API uses Promises instead of Events like the Filereader API, so much less troubles with closures. Also the Arrow function (x=>) and iterator for of, make the code much more concise.

    Check support.

    Use Fetch API

    Also using the Fetch API Response Object it can be done more easy.

    for (let file of files){
     (new Response(file)).text().then(x=>console.log(file.name,x));
    }
    

    Note of the missing Array [] in the constructor.

    Also check support.

    0 讨论(0)
提交回复
热议问题