javascriptarraysstringfilefilelist

DOT.files in javascript? What does it mean?


I'm currently working off a sample code found online of a file reader which I need some assistance deciphering.

function readBlob(opt_startByte, opt_stopByte) {

    var files = document.getElementById('files').files;
    if (!files.length) {
        alert('Please select a file!');
        return;
    }
    //var file = files[0];
    var reader = new FileReader();
    reader.readAsText(files[0], "UTF-8");

In this part of the code, I want to know how javascript interprets the .files in document.getElementById('files').files or what the variable files is stored as.

I printed out files right after I set it to see what it prints in the console and I still don't understand what it means. enter image description here

What I'm trying to do is change files so it loops through an array to get every specific value instead of just one.


Solution

  • When looking at a console log of an object if it is an instance object (ie made from a constructor function) it will have a name preceding it's details. In this case that name is FileList. You can use that name in a search query to look up information about it's structure and other details.

    For instance searching "javascript FileList" one of the top results will be MDN's documentation about that structure.

    Simply it is just an array-like object. Meaning it has numeric property keys that hold it's items (files), and a length property telling the number of items it holds.

    With this you should realize you can use a regular for loop to iterate over its contents

    for(let i=0; i<files.length; i++){
      let file=files[i];
      console.log(file.name);
    }
    

    Note FileList also has a Symbol.iterator meaning it can create its own iterator. So this means you can also use a for ... of loop with the structure

    for(let file of files){
      console.log(file.name);
    }
    

    If you are wanting to read in each file with FileReader you will need to call the code you were using inside a loop

    for(let file of files){
        var reader = new FileReader();
        reader.onloadend = function(){
           //store data somewhere
        }
        reader.readAsText(file, "UTF-8");
    }