Search code examples
javascriptjqueryhtmlhtml5-filesystem

Undefined file in javascript array when grabbing files from an input type="file" tag


I have this really weird issue while grabbing images from an input tag, and I can't figure out why. Here's the code:

var files,
    fileCounter = 0,
    fileArray = [];

$("#fc").on("change", function() {
    files = $("#fc")[0].files;
    console.log(files);
    for (var i = 0; i < files.length; i++) {
        fileArray[fileCounter] = files[fileCounter];
        fileCounter++;
        console.log(fileArray);
    }
});

The html is pretty simple:

<input type="file" id="fc" multiple="multiple" />

The fileArray should be grabbing each image as I add it, but it will only grab 2 before listing files as "undefined". No clue why.


Solution

  • The issue you are having on subsequent additions to fileArray stems from your index value in the assignment:

    fileArray[fileCounter] = files[fileCounter];
    

    Because fileCounter is essentially the length of the fileArray, after the first loop any subsequent additions would cause fileCounter to start at values greater than 0. Therefore when you tried to assign files[fileCounter] to the fileArray, the index you were selecting was greater than 0 which for a single file array would mean you were referencing an undefined element.

    That said, you don't really need those counters but just the array:

    var fileArray = [];
    
    $("#fc").on("change", function() {
      var files = $("#fc")[0].files;
      console.log(files);
      for (var i = 0, len = files.length; i < len; i++) {
        fileArray.push(files[i]);
        console.log(fileArray);
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="file" id="fc" multiple="multiple" />

    You could even simplify this further by using concat and slice:

    var fileArray = [];
    
    $("#fc").on("change", function() {
      var files = $("#fc")[0].files;
      console.log(files);
      // convert `files` to an array and concat it to `fileArray`
      fileArray = fileArray.concat(Array.prototype.slice.call(files));
      console.log(fileArray);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="file" id="fc" multiple="multiple" />