Search code examples
javascripthtmlformsinputfilelist

multiple file input html not working


I have the following code for multiple file input

<form action="" enctype = "multipart/form-data" method="post" name="login">

<input type = "file" name = "photo[]" id = "files" multiple onchange =  "handleFileSelect(this.files)"/><br/>
<div id="selectedFiles"></div>
<input type="submit" value="Sign In">
</form>

The javascript equivalent function is.

selDiv = document.querySelector("#selectedFiles");
function handleFileSelect(e) {
    if(!this.files) return;

    selDiv.innerHTML = "";

    var files = e;
    for(var i=0; i<files.length; i++) {
        var f = files[i];
        selDiv.innerHTML += f.name + "<br/>";

    }

}

What I am getting is upon uploading the second file. The FileList gets overwritten and instead of having 2 files, second file is present in the FileList. Here FileList is passed by this.files.

Also upon passing to the server only second image is passed. I have googled throughly but could not find answer. I would appreciate if anyone could help.


Solution

  • I ran into the same problem. Thanks for the question and answer. I managed to add several files by adding to the DOM input type file and delegating the click to the detached element :

    <form method="POST" enctype="multipart/form-data" action="/echo/html">
      <button class="add">
        Add File
      </button>
      <ul class="list">
      </ul>
      <button>
          Send Form
      </button>
    </form>
    

    With the javascript :

    $('form button.add').click(function(e) {
        e.preventDefault();
        var nb_attachments = $('form input').length;
        var $input = $('<input type="file" name=attachment-' + nb_attachments + '>');
        $input.on('change', function(evt) {
            var f = evt.target.files[0];
            $('form').append($(this));
            $('ul.list').append('<li class="item">'+f.name+'('+f.size+')</li>');
        });
        $input.hide();
        $input.trigger('click');
    });
    

    It is working with Edge, Chrome 50 and firefox 45, but I don't know the compatibility with older versions or other browsers.

    See the this fiddle.