David Tan David Tan - 4 months ago 15
HTML Question

How to work with FileList (from <input type="file">) in Javascript?

In this W3schools example,

console.log
on the input element reveals a FileInput object:

FileList {0: File, 1: File, length: 2}


How can I work with this? The example demonstrates accessing the file, but every time a user selects new files, the old files disappear. How can I create a new empty FileList and copy it over, so that a user can add more files to the FileList?

I tried this, but it results in two FileList objects, rather than one FileList with all the files:

var fileStore = x.files;

function myFunction(){
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
fileStore += x.files;
console.log(x.files);
console.log(fileStore);

Answer

Untested, but this should work

var fileStore = [];

function myFunction(){
    var txt = "";
    if ('files' in x) {
        if (x.files.length == 0) {
            txt = "Select one or more files.";
        } else {
            fileStore.push.apply(fileStore,x.files);
            console.log(x.files);
            console.log(fileStore);

More on Function::apply

More on Array::push

Comments