Javascript Javascript从具有多个属性的文件输入元素中获取文件数量及其文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6171013/
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
Javascript get number of files and their filenames from file input element with multiple attribute?
提问by Stann
I have a file input with the multiple="multiple"
attribute to allow users to select multiple files at once. I would like to display selected file names and their count prior to upload however I'm not sure how to get this information from file input element using javascript?
我有一个带有multiple="multiple"
属性的文件输入,允许用户一次选择多个文件。我想在上传之前显示选定的文件名及其计数,但是我不确定如何使用 javascript 从文件输入元素中获取此信息?
<input type="file" id="fileElementId" name="files[]" size="20" multiple="multiple" />
I've tried this:
我试过这个:
document.getElementById('fileElementId').value
But this only returns one file name when I select multiple files.
Using JavaScript is how do I retrieve the number of selected files and their names from a file input element with a multiple
attribute?
但是当我选择多个文件时,这只会返回一个文件名。使用 JavaScript 如何从具有multiple
属性的文件输入元素中检索所选文件的数量及其名称?
回答by Pointy
In new browsers that support the HTML5 file stuff, your <input>
element will have a "files" property. That will give you a "FileList" reference, which has a ".length" property. There's also an access method called ".item()" on the "FileList" instance, and it takes an integer arg to access individual "File" elements. Those have a ".name" property.
在支持 HTML5 文件内容的新浏览器中,您的<input>
元素将具有“文件”属性。这会给你一个“FileList”引用,它有一个“.length”属性。在“FileList”实例上还有一个称为“.item()”的访问方法,它需要一个整数参数来访问单个“File”元素。那些具有“.name”属性。
So:
所以:
var inp = document.getElementById('fileElementId');
for (var i = 0; i < inp.files.length; ++i) {
var name = inp.files.item(i).name;
alert("here is a file name: " + name);
}
This will of course not work in older IE versions, and I'm not even sure how thorough the Safari and Chrome support is; however, if you're writing pages with "multiple" set on your file inputs you're already dancing on the edge :-)
这当然不适用于较旧的 IE 版本,我什至不确定 Safari 和 Chrome 支持有多彻底;但是,如果您在文件输入上设置了“多个”设置的页面,那么您已经在边缘跳舞了:-)
回答by devmatt
This is untested, but you could try:
这是未经测试的,但您可以尝试:
$('#fileElementId').get(0).files;
or
或者
document.getElementById('fileElementId').files;
回答by I am the Most Stupid Person
The second answer was wrong.
第二个答案是错误的。
Answer should be document.getElementById('fileElementId').files.length;
instead of document.getElementById('fileElementId').files;
.
答案应该是document.getElementById('fileElementId').files.length;
而不是document.getElementById('fileElementId').files;
。