Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

javascript - Is it possible to update FileList?

I have:

<input type="file" id="f" name="f" onchange="c()" multiple />

Every time the user selects a file(s), I build a list of all the selected files by pushing each element of f.files to an array:

var Files = [];
function c() {
  for (var i=0;i<this.files.length;i++) {
    Files.push(this.files[i]);
  };
}

At form submit, f.files contains only the item(s) from the last select action, so I will need to update f.files with the list of FileList items I have accumulated:

const upload=document.getElementById("f");
upload.files = files;

But the second line gives:

Uncaught TypeError: Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.

It is not happy that I am assigning it an array. How can I construct a FileList object from the list of FileList elements I have earlier collected?

Side question: I thought Javascript uses dynamic types. Why is it complaining about the wrong type here?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't modify a Filelist, but you can create a new one using a DataTransfer object, and if you wish you can copy your data into it to create a duplicate with the specific change you want to make.

let list = new DataTransfer();
let file = new File(["content"], "filename.jpg");
list.items.add(file);

let myFileList = list.files;

You can then set it as the file attribute of the DOM node:

fileInput.files = myFileList;

If you wished, you could iterate over your old FileList, copying files to the new one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...