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

前端 未结 3 698
逝去的感伤
逝去的感伤 2020-11-27 03:30

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 th

相关标签:
3条回答
  • 2020-11-27 04:03

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

    0 讨论(0)
  • 2020-11-27 04:03

    The second answer was wrong.

    Answer should be document.getElementById('fileElementId').files.length; instead of document.getElementById('fileElementId').files;.

    0 讨论(0)
  • 2020-11-27 04:06

    This is untested, but you could try:

        $('#fileElementId').get(0).files;
    

    or

        document.getElementById('fileElementId').files;
    
    0 讨论(0)
提交回复
热议问题