Reputation: 223
I am here to know that How to add/upload/choose multiple files from one input tag that is multiple but after selecting again all previous selection were removed or override. what I want is.
Upvotes: 4
Views: 13263
Reputation: 3503
You can hide the input[type=file] and provide an UI that interacts with the input in order to select new files and manage separately a list of files.
So you can:
add a hidden input <input id="myInput" type="file" multiple style="display:none" />
Provide a good looking UI with a button that calls the myInput.click() in order to open the prompt
subscribe to input change event and get the myInput.files and store them in an array or collection
to upload all files via AJAX just create a FormData and append all the files then pass FormData instance to the ajax call (eg: $ajax({...data: formData...})).
EDITED:
Sample Behavior:
Sample HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input id="myInput" type="file" multiple style="display:none" />
<button id="myButton" type="button" style="border-radius: 5px; background-color: #fff; color: green;">+ Add Files</button>
<button id="mySubmitButton" type="button" style="border-radius: 5px; background-color: #fff; color: green;">Send Files</button>
<div id="myFiles"></div>
</body>
</html>
Sample Script:
$(function(){
let inputFile = $('#myInput');
let button = $('#myButton');
let buttonSubmit = $('#mySubmitButton');
let filesContainer = $('#myFiles');
let files = [];
inputFile.change(function() {
let newFiles = [];
for(let index = 0; index < inputFile[0].files.length; index++) {
let file = inputFile[0].files[index];
newFiles.push(file);
files.push(file);
}
newFiles.forEach(file => {
let fileElement = $(`<p>${file.name}</p>`);
fileElement.data('fileData', file);
filesContainer.append(fileElement);
fileElement.click(function(event) {
let fileElement = $(event.target);
let indexToRemove = files.indexOf(fileElement.data('fileData'));
fileElement.remove();
files.splice(indexToRemove, 1);
});
});
});
button.click(function() {
inputFile.click();
});
buttonSubmit.click(function() {
let formData = new FormData();
files.forEach(file => {
/* here I just put file as file[] so now in submitting it will send all
files */
formData.append('file[]', file);
});
console.log('Sending...');
$.ajax({
url: 'https://this_is_the_url_to_upload_to',
data: formData,
type: 'POST',
success: function(data) { console.log('SUCCESS !!!'); },
error: function(data) { console.log('ERROR !!!'); },
cache: false,
processData: false,
contentType: false
});
});
});
Upvotes: 15