javascriptdomfilelist

Split FileList into individual file input elements


Is it possible to split a FileList instance (from a drop event, event.dataTransfer.fileList), and assing each file within it to an individual <input type="file" ... /> element?

For example, to assign all files (1 or more...) from a drop event to an input element fileInputElement, you would:

function dropHandler(event) {
  fileInputElement.files = event.dataTransfer.files;
}

I'm looking for something like:

function dropHandler(event) {
  // assume fileEls is an array of input[type=file] elements
  for (var i = 0; i < event.dataTransfer.files.length; i++) {

    // yep, FileList.push doesn't exist..
    fileEls[i].files.push(event.dataTransfer.files.item(i));

    // and this (imagined) FileList constructor is not available...
    fileEls[i].files = new FileList([event.dataTransfer.files.item(i)]);
  }
}

A signs point to nope, can't do it...


Solution

  • You can create a new FileList through DataTransfer

    function dropHandler(event) {
      // assume fileEls is an array of input[type=file] elements
      for (var i = 0; i < event.dataTransfer.files.length; i++) {
    
        // Create a new DataTransfer
        var dataTransfer = new DataTransfer();
    
        // Add the items
        dataTransfer.items.add(event.dataTransfer.files.item(i));
    
        // Get the FileList
        fileEls[i].files = dataTransfer.files;
    
      }
    }