栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在FileList对象上设置File对象和length属性,同时文件也反映在FormData对象上?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在FileList对象上设置File对象和length属性,同时文件也反映在FormData对象上?

编辑:

正如 OP 所证明的 那样,在他们的要旨中,实际上有一种方法可以…

该数据传递构造函数目前只有闪烁的支持,以及FF=62](https://bugzilla.mozilla.org/show_bug.cgi?id=1351193)),应该创建一个可变的文件清单(目前铬总是返回一个新的文件清单,但它其实并不重要,对我们来说),通过DataTransferItemList访问。

如果我没记错的话,这是目前唯一遵循规范的方法,但是Firefox在实现ClipboardEvent构造函数时存在一个错误,在该示例中,相同的DataTransferItemList设置为read /write模式,从而可以解决此问题。对于FF<62。我不确定我对这些规范的解释,但我认为通常无法正常访问该规范)。

因此, guest271314 发现在FileList上设置任意文件的方式如下:

const dT = new ClipboardEvent('').clipboardData || // Firefox < 62 workaround exploiting https://bugzilla.mozilla.org/show_bug.cgi?id=1422655  new DataTransfer(); // specs compliant (as of March 2018 only Chrome)dT.items.add(new File(['foo'], 'programmatically_created.txt'));inp.files = dT.files;<input type="file" id="inp">

这一发现导致了这项新的提议,即默认情况下使FileList对象可变,因为不再有没有理由不这样做。


上一个(过时的)答案

你不能 不能通过脚本修改FileList对象*。

您只能将输入的FileList交换到另一个FileList,但不能修改它

除了用清空

input.value = null
)。

而且,您既不能从头开始创建FileList
,也不能只创建不能创建的DataTransfer对象,而是

input[type=file]
将创建此类对象。

为了向您展示即使将

input[type=file]
FileList 设置为另一输入的输入,也不会创建新的FileList:

var off = inp.cloneNode(); // an offscreen inputinp.onchange = e => {  console.log('is same before', inp.files === off.files);  off.files = inp.files; // now 'off' does have the same FileList as 'inp'  console.log('is same after', inp.files === off.files);  console.log('offscreen input FileList', off.files);  console.log('resetting the offscreen input');  off.value = null;  console.log('offscreen input FileList', off.files);  console.log('inscreen input FileList', inp.files);}<input type="file" id="inp">

哦,我差点忘了FormData部分,我真的不明白说的是事实…

因此,如果我一切正常,那么您只需要

FormData.append()

var fd = new FormData();fd.append("files[]", new Blob(['a']), 'a.txt');fd.append("files[]", new Blob(['b']), 'b.txt');for(let pair of fd.entries()) {   console.log(pair[0], pair[1]);}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407922.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号