24

I am using Struts2 to upload multiple files:

<s:file name="files" multiple="multiple" />

When I select multiple files it displays the number of files, eg. 3 files.

The project requirements are that the user should be able to see what files he selected before uploading.

Is it possible to display the selected files names in a list or maybe in the control itself ?

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Pradnya
  • 649
  • 2
  • 6
  • 17

1 Answers1

62

You can use the HTML5 files property of the <input type="file" /> element like follows:

updateList = function() {
    var input = document.getElementById('file');
    var output = document.getElementById('fileList');
    var children = "";
    for (var i = 0; i < input.files.length; ++i) {
        children += '<li>' + input.files.item(i).name + '</li>';
    }
    output.innerHTML = '<ul>'+children+'</ul>';
}
<input type="file" multiple
       name="file" 
         id="file" 
   onchange="javascript:updateList()" />

<p>Selected files:</p>

<div id="fileList"></div>
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • @Andrea Ligios Yes it is a CSS definitely, but it is rendering through this script. You can run the code snippet and inspect element. you can see that.
    • filename1
    • filename2
    • – Naveenbos Feb 14 '20 at 15:31
    • @Naveenbos you're right, there was an HTML (not CSS) problem. Probably calling `.innerHTML = "
        "` resulted in the browser adding the closing tag too... I've edited the script, enjoy it.
      – Andrea Ligios Feb 14 '20 at 15:42
    • @Andrea Ligios This code is working perfectly. Is it possible to show the image along with the name using this code? – Naveenbos Feb 14 '20 at 16:26
    • @Naveenbos, you should really upvote the answer, since it helped... and then open a new question (which, as-is, gets a fat chance of being closed for being a *"gimme the code"* type of question) – Andrea Ligios Feb 14 '20 at 16:42
    • then how to make a remove button there that "removed' the selected file? – EMPaguia Apr 17 '21 at 07:17
    • The question is not clear, and it would be better if you ask it as a brand new question – Andrea Ligios Apr 17 '21 at 17:05