javascript 如何更改文件输入的文件列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5632629/
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-25 17:50:53  来源:igfitidea点击:

how to change the file input's filelist

javascripthtmlset

提问by dave

I have this inputof type "file", and I want to change its fileslist. Example:

我有这个input类型"file",我想更改它的files列表。例子:

<input type = "file" id = "fileinput" />
<script type = "text/javascript>
  document.getElementById("fileinput").files = [10];
</script>

The problem is that the fileinputelement's fileslist is not set. How do I do it?

问题是未设置fileinput元素的files列表。我该怎么做?

回答by odrm

For security reasons, browsers prevent javascript from changing the files which will be uploaded: only the user can select files via the user interface. This is to prevent an evil script to upload /etc/passwd, for example, without the user knowing.

出于安全原因,浏览器会阻止 javascript 更改将要上传的文件:只有用户可以通过用户界面选择文件。这是为了防止恶意脚本/etc/passwd在用户不知情的情况下上传。

The one exception is that calling "reset" on the form will clear the file or filelist, but you can never add to programmatically.

一个例外是在表单上调用“重置”将清除文件或文件列表,但您永远无法以编程方式添加。

回答by Marcel Korpel

What you want is using the multipleattribute on the inputelement. That way, in newer browsers user will be able to select multiple files to upload.

您想要的是使用元素multiple上的属性input。这样,在较新的浏览器中,用户将能够选择多个文件进行上传。