How to Remove a File from a JavaScript FileList?

ā€¢

Sometimes, we want to remove a file from a JavaScript FileList object.

In this article, weā€™ll look at how to remove a file from a JavaScript FileList object.

Use the Spread Operator

One way to remove a file from a JavaScript FileList is to use the spread operator to convert the FileList to an array.

Then we can callĀ spliceĀ to remove the file we want.

For instance, we can write the following HTML:

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

We addĀ multipleĀ to let select multiple files.

Then we can remove one of the items selected by writing:

const input = document.getElementById('files')
input.addEventListener('change', () => {
  const fileListArr = \[...input.files]
  fileListArr.splice(1, 1)
  console.log(fileListArr)
})

We get the file input element withĀ getElementByIdĀ .

We spreadĀ input.filesĀ into an array.

Then we callĀ spliceĀ on the array with index 1 as the first argument and we specify that we remove 1 item with the 2nd arguemnt.

Therefore,Ā fileListArrĀ has the 1st and 3rd file listed.

Use the Array.from Method

We can replace the spread operator with theĀ Array.fromĀ method.

For instance, we can write:

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

And:

const input = document.getElementById("files");
input.addEventListener("change", () => {
  const fileListArr = Array.from(input.files);
  fileListArr.splice(1, 1);
  console.log(fileListArr);
});

to do the same thing.

The only difference is that the spread operator is replaced withĀ Array.fromĀ .

Conclusion

One way to remove a file from a JavaScript FileList is to use the spread operator to convert the FileList to an array.

Also, we can replace the spread operator with theĀ Array.fromĀ method.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics