Javascript 选择多个文件时获取 input type="file" 值

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

Get input type="file" value when it has multiple files selected

javascripthtml

提问by spuas

Possible Duplicate:
Retrieving file names out of a multi-file upload control with javascript

可能的重复:
使用 javascript 从多文件上传控件中检索文件名

From HTML5 input type="file" allows users to choose multiple files by adding the multiple="multiple" :

从 HTML5 input type="file" 允许用户通过添加 multiple="multiple" 来选择多个文件:

<input type="file" multiple="multiple" />

My question is: how can I get the value of that input? When using the .value it only returns the filename of the first file selected, but when choosing more than one I am not able to view the other ones.

我的问题是:如何获得该输入的值?当使用.value时,它只返回所选的第一个文件的文件名,但在选择多个时,我无法查看另一个文件。

What I have:

我拥有的:

<input type="file" multiple="multiple" onchange="alert(this.value)"
     onmouseout="alert(this.value) />

which as I told you, is only showing the name of one of the selected files.

正如我告诉你的,它只显示所选文件之一的名称。

NOTE: I don't want to edit the value (I know that is not possible) only the name of the files

注意:我不想只编辑文件名的值(我知道这是不可能的)

Thanks!

谢谢!

回答by foxy

The files selected are stored in an array: [input].files

选择的文件存储在一个数组中: [input].files

For example, you can access the items

例如,您可以访问项目

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

对于使用 jQuery 的人来说,这同样简单

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

回答by Wladimir Palant

You use input.filesproperty. It's a collection of File objectsand each file has a nameproperty:

使用input.files财产。它是File 对象的集合,每个文件都有一个name属性:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"