Is it possible to update FileList?

It's like you said

Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.

you can only set the files with a FileList instance, unfortunately the FileList is not constructible or changeable, but there is a way to get one in a round about way

/**
 * @params {File[]} files Array of files to add to the FileList
 * @return {FileList}
 */
function FileListItems (files) {
  var b = new ClipboardEvent("").clipboardData || new DataTransfer()
  for (var i = 0, len = files.length; i<len; i++) b.items.add(files[i])
  return b.files
}

var files = [
  new File(['content'], 'sample1.txt'),
  new File(['abc'], 'sample2.txt')
];


fileInput.files = new FileListItems(files)
console.log(fileInput.files)
<input type="file" id="fileInput" multiple />

doing this will trigger a change event, so you might want to toggle the change event listener on and off


You can't modify a Filelist, but you can create a new one using a DataTransfer object, and if you wish you can copy your data into it to create a duplicate with the specific change you want to make.

let list = new DataTransfer();
let file = new File(["content"], "filename.jpg");
list.items.add(file);

let myFileList = list.files;

You can then set it as the file attribute of the DOM node:

fileInput.files = myFileList;

If you wished, you could iterate over your old FileList, copying files to the new one.

Tags:

Javascript