Question

I have a function which handles drag-dropping files on my page:

function createDropHandlers() {
  var target = document;
  if (target === null) {
    return false;
  }

  // attach the 'dragover' event to the container
  target.addEventListener('dragover', function(event) {
    event.preventDefault();
  }, true);

  // attach the 'drop' event to the container
  target.addEventListener('drop', function(event) {
    event.preventDefault();
    var files = event.dataTransfer.files;

    // if (files.length > 3)
    // do something like
    // files.slice(files.length-3, files.length);

    for (var i = 0; i < files.length; i++) {
        processFile(files[i]);
        // ...
    }
  }, true);
}

What I'd like to do is before my for loop (and before "processing" files in any way) to check if more than 3 files were dragged, and if so, just slice the "array" to last 3 elements. I know that FileList is read only so I'm not sure what are my options here to achieve this...
I will not upload files, and after "processing" them and I won't need File objects whatsoever. All I need to do is to check if files are audio files, read some metadata from them and display metadata on page.

Was it helpful?

Solution

slice() is a method from the prototype of Array. Whereas it returns a new array, it may not be in the FileList prototype. You can use the Array.prototype.slice method and apply it on the filelist:

Array.prototype.slice.call( fileList ); //will return an array-copy of the filelist
Array.prototype.slice.call( fileList, 0, 3 ); //Then simply use the slice arguments at your convenience

You can use (and will see often in js-libraries code) this trick on arguments, also. Please note that slice doesn't modify the original object, like splice() does.

you can check out https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice#Array-like for an explanation on MDN.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top