Wednesday, August 5, 2020

FileList.forEach

We can't use forEach on FileList data structure. FileList is an object, not an array. To convert it to array, we have to use Object.values, or use spread operator:
function handleFiles(files) {
    console.log(files);
    alert(Array.isArray(files)); // false
    alert(Array.isArray(Object.values(files))); // true
    alert(Array.isArray([...files])); // true

    // this won't work:
    //      files.forEach(uploadFile);

    [...files].forEach(uploadFile);
}

function uploadFile(file) {
    alert('uploading ' + file.name);
}

No comments:

Post a Comment