I have an API in Django where on one page the user can uplaod files. I am using this HTML code:
I want that after the selection the files are displayed and that the user can remove the files that he wants before uploading. To do it, I help me from what I could find on internet, I try to use this jQuery code that works to display and remove the files from the list on the webpage. However when I submit, it uploads the first selection with the files that were removed.
function updateList() {
var input = document.getElementById('id_Filename');
var list = [];
for (var i = 0, len = input.files.length; i < len; ++i) {
list.push(input.files.item(i));
}
outputList(list);
}
function outputList(list) {
var output = document.getElementById('fileselect');
while (output.hasChildNodes()) {
output.removeChild(output.lastChild);
}
var nodes = document.createElement('ul');
for (var i = 0, len = list.length; i < len; ++i)(function(i) {
var node = document.createElement('li');
var filename = document.createTextNode(list[i].name);
var removeLink = document.createElement('a');
removeLink.href = 'javascript:void(0)';
removeLink.innerHTML = 'Remove';
removeLink.onclick = function() {
list.splice(i, 1); // remove item
outputList(list);
}
node.appendChild(filename);
node.appendChild(removeLink);
nodes.appendChild(node);
})(i);
output.appendChild(nodes);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="Filename" class="form-control" multiple="" onchange="javascript:updateList()" maxlength="255" id="id_Filename">
<button type="submit" class="btn btn-primary" id="submitupload">Charger
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-upload" viewBox="0 0 16 16">
<path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"></path>
<path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"></path>
</svg>
</button>
<div class="block-file-selection">
<p>
Selected files :
</p>
<div id="fileselect">
</div>
</div>
What is wrong or what is missing ?
Thank you