本文介绍了是否可以更新FileList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

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

每次用户选择文件时,我都会按以下方式构建所有选定文件的列表:将 f.files 的每个元素推送到数组:

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]);
  };
}

在表单提交时, f.files 仅包含上次选择操作中的项目,因此我需要使用 FileList列表更新 f.files 我积累的项目:

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;

但第二行给出:

我将它分配给一个数组并不高兴。如何从我之前收集的 FileList 元素列表中构造 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?

附带问题:我认为Javascript使用动态类型。为什么在这里抱怨错误的类型?

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

推荐答案

就像你说的那样

你只能使用FileList设置文件,不幸的是FileList不是可构造的或可更改的,但有一种方法可以在一轮中获得一个方式

you can only set the files with a FileList, unfortunately the FileList is not constructable or changeable, but there is a way to get one in a round about way

// Used for creating a new FileList in a round-about way
function FileListItem(a) {
  a = [].slice.call(Array.isArray(a) ? a : arguments)
  for (var c, b = c = a.length, d = !0; b-- && d;) d = a[b] instanceof File
  if (!d) throw new TypeError("expected argument to FileList is File or array of File objects")
  for (b = (new ClipboardEvent("")).clipboardData || new DataTransfer; c--;) b.items.add(a[c])
  return b.files
}

var files = [
  new File(['content'], 'sample1.txt'),
  new File(['abc'], 'sample2.txt')
];

fileInput.files = new FileListItem(files)
<input type="file" id="fileInput" multiple />

执行此操作将触发更改事件,因此您可能希望打开和关闭更改事件侦听器

doing this will trigger a change event, so you might want to toggle the change event listener on and off

这篇关于是否可以更新FileList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 13:14