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.