Saturday, May 25, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  192] [ 4]  / answers: 1 / hits: 16157  / 8 Years ago, sun, july 24, 2016, 12:00:00

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.


More From » html

 Answers
9

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.


[#61266] Thursday, July 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dakotahs

Total Points: 605
Total Questions: 104
Total Answers: 113

Location: Hungary
Member since Wed, Nov 9, 2022
2 Years ago
;