Create Multiple Input Type="file" Elements With Their Corresponding Value (filelist) According To The Main Input Type="file" (multiple) Element
I have this code where I loop unto files from a multiple input file type What I'm trying to achieve, is clone the main input (#main-input) and gives a value (file) base on the loo
Solution 1:
Yes, the requirement is possible. You will need to create a new FileList
for each File
object, then set .files
property of the <input type="file">
element to the FileList
populated with the File
object.
The code at below returns the same results at Chromium 62+ and Firefox 57+, see comments by @Kaiido for evaluations at Safari and Edge.
// FileList.jsclassFileList {
constructor(...items) {
// flatten rest parameter
items = [].concat(...items);
// check if every element of array is an instance of `File`if (items.length && !items.every(file => file instanceofFile)) {
thrownewTypeError("expected argument to FileList is File or array of File objects");
}
// use `ClipboardEvent("").clipboardData` for Firefox, which returns `null` at Chromium// we just need the `DataTransfer` instance referenced by `.clipboardData`const dt = newClipboardEvent("").clipboardData || newDataTransfer();
// add `File` objects to `DataTransfer` `.items`for (let file of items) {
dt.items.add(file)
}
return dt.files;
}
}
document.querySelector("input[type=file]")
.onchange = e => {
for (let file of e.target.files) {
const input = document.createElement("input");
input.type = "file";
input.files = newFileList(file);
document.body.appendChild(input);
}
}
<inputtype="file"multiple>
// FileList.jsfunction_FileList(items) {
// flatten rest parameter
items = [].concat.apply([], [items]);
// check if every element of array is an instance of `File`if (items.length
&& !items.every(function(file) {
return file instanceofFile})) {
thrownewTypeError("expected argument to FileList is File or array of File objects");
}
// use `ClipboardEvent("").clipboardData` for Firefox, which returns `null` at Chromium// we just need the `DataTransfer` instance referenced by `.clipboardData`var dt = newClipboardEvent("").clipboardData || newDataTransfer();
// add `File` objects to `DataTransfer` `.items`for (var i = 0; i < items.length; i++) {
dt.items.add(items[i])
}
return dt.files;
}
document.querySelector("input[type=file]")
.onchange = function(e) {
for (var i = 0; i < e.target.files.length; i++) {
var input = document.createElement("input");
input.type = "file";
input.files = new_FileList(e.target.files[i]);
document.body.appendChild(input);
}
}
<inputtype="file"multiple>
Post a Comment for "Create Multiple Input Type="file" Elements With Their Corresponding Value (filelist) According To The Main Input Type="file" (multiple) Element"