javascript 输入类型=文件多个,删除项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19666064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:24:09  来源:igfitidea点击:

input type=file multiple, delete items

javascripthtml

提问by tim

html:

html:

<input accept="image/*" class="" id="my_pics" multiple="multiple" name="pics" required="true" type="file" />

js:

js:

var files = document.getElementById('my_pics').files;
files.splice(1,2)
//TypeError: Object #<FileList> has no method 'splice'
delete files.item(2)
// true, but nothing happens with "2"
delete files[2]
// false, result is the same

I have a form with multiple file, I need to upload on server only limited number of images (for example, 5) in one input, but my code doesnt work.

我有一个包含多个文件的表单,我只需要在一次输入中在服务器上上传有限数量的图像(例如 5 个),但我的代码不起作用。

How to fix it? Thanks.

如何解决?谢谢。

回答by Alex W

You can't delete that because it's a Fileobject pointed to in the FileListobject, hence the error above. However, you can iterate over the FileListand only push the items that you want onto an array, which you can then modify:

您无法删除它,因为它是File对象中指向的FileList对象,因此出现上述错误。但是,您可以迭代FileList并只将您想要的项目推送到数组中,然后您可以修改它:

var files = document.getElementById('my_pics').files;
var newList = [];

for(var i = 0; i < files.length; i++)
{
    if(i !== 2)
    {
        newList.push(files.item(i));
    }
}

As you can see from this answer, you can't deletethe actual object. Only the reference to the object can be deleted. So, even if it worked for the FileListobject, which it doesn't, it would only set that element equal toundefined.

正如你从这个答案中看到的,你不能delete真正的对象。只能删除对对象的引用。因此,即使它对FileList对象有效,但对对象无效,它只会将该元素设置为等于undefined.