问题
I have a multiple file input. I want my customers to choose multiple files when they click on 'Choose files' (I think it is done) and if they forget to select some files, I want my code to enable selecting new files (done) AND add that data to the data that they have selected before (couldn't solve it).
How can I append the new files to the list?
Just to give you the context: my goal after this is to send each file with AJAX to my PHP server.
$("#upload-form").submit(function(e) {
$('#displayFileNames').html('');
console.log('Currently in files.');
var files = $('#myFileInput')[0].files;
for (var i = 0; i < files.length; i++){
$('#displayFileNames').append(files[i].name + '</br>');
console.log(files[i].name);
}
// Send data with AJAX.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
<input id='myFileInput' class='file-input' type='file' name='file[]' multiple='multiple' />
<input type='submit' value="See what's in there" />
</form>
<div id="displayFileNames"></div>
Any help, hint is appreciated!
回答1:
I believe the same element cant be used for the mentioned use. Here is a workaround. On a file input click append another file input and hide the current one.
$("#seebtn").click(function(e) {
$('#displayFileNames').html('');
var domArray = document.getElementsByClassName('file-input');
for (var i = 0; i < domArray.length; i++) {
var files = domArray[i].files;
for (var j = 0; j < files.length; j++){
$('#displayFileNames').append(files[j].name + '</br>');
}
};
// Send data with AJAX.
});
function myFunction(obj) {
$(obj).hide();
$("#upload-form").append("<input class='file-input' type='file' onclick='myFunction(this)' name='file[]' multiple='multiple' />");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value="See what's in there" id="seebtn">see</button>
<form id='upload-form' action='' method='post' enctype='multipart/form-data'>
<input id='myFileInput' class='file-input' type='file' name='file[]' onclick="myFunction(this)" multiple='multiple' />
</form>
<div id="displayFileNames"></div>
来源:https://stackoverflow.com/questions/29394126/open-several-times-multiple-file-input-without-losing-earlier-selected-files