Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

Javascript get number of files and their filenames from file input element with multiple attribute?

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?

<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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...