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.