It is possible to set .files
property of <input type="file">
element to a FileList
from for example a different <input type="file">
element .files
property or DataTransfer.files
property. See Make .files settable #2866, What happens between uploading a file to an HTML form and submitting it?.
FileList
object has a Symbol.iterator
property which we can use to set a File
object which is iterable, however the .files
.length
is still set to 0
and passing a <form>
having <input type="file">
set where the .files
is set using the above approach yields a File
object having .size
set to 0
.
How to set the File
at FileList
and set .length
of FileList
to the number of files set, where the files are set at FormData()
object?
const input = document.createElement("input");
const form = document.createElement("form");
const [...data] = [
new File(["a"], "a.txt")
, new File(["b"], "b.txt")
];
input.type = "file";
input.name = "files";
input.multiple = true;
// set `File` objects at `FileList`
input.files[Symbol.iterator] = function*() {
for (const file of data) {
yield file
};
};
form.appendChild(input);
const fd = new FormData(form);
for (const file of input.files) {
console.log(file); // `File` objects set at `data`
}
for (const [key, prop] of fd) {
// `"files"`, single `File` object having `lastModified` property
// set to a time greater than last `File` object within `data`
// at Chromium 61, only `"files"` at Firefox 57
console.log(key, prop);
}
console.log(input.files.length); // 0