Categories
JavaScript Answers

How to Remove a File from a JavaScript FileList?

Spread the love

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 .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

5 replies on “How to Remove a File from a JavaScript FileList?”

That console log isn’t the FileList object though, you’ve only removed an item from fileListArr. How do you then make the FileList the same as the fileListArr?

You have some good posts on this. Thanks. For security reasons I get that the only files we can assign to a file input are files actually selected by the visitor via either drop or browse actions on their part. We should not be able to add additional files to the FileList or replace files they designated with other files on their computer in the FileList they submitted to us via their own browses and/or drop selections.

However, it seems like we should be able to filter the files selected by the user via browse or drop and eliminate ones that aren’t acceptable to us ie wrong types, too big, etc etc. via js on the front end instead of having to post those problematic files to our server and have php weed them out on the back end. Is there a way to do this? Seems like that would actually be a security enhancement. ie partially accepting the files instead of all or none. Thanks for any ideas.

Yes. You can get the files from the $_FILES array and filter them there with a loop or array functions.

You didn’t get what Tristam Pedetteri was saying, there’s no way to actually mutate the fileList objects within it. You can only clone them and mutate like you just did

Leave a Reply

Your email address will not be published. Required fields are marked *