I am using a multi-file upload with a form in django. I want to diplay the selected files in a list and that the user is able to remove the files that he wants before uploading. There is a delet button for it.
I based on a post to do on Jquery. It works to display the files, and remove them from the list that is diplayed on the webpage. However the files that are removed are still uploaded even if the are not display in the list.
html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"
integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="
crossorigin="anonymous"
referrerpolicy="no-referrer">
</script>
<div> <input type="file" name="Filename" class="form-control" multiple="" onchange="javascript:updateList()" maxlength="255" id="id_Filename"> </div>
<div class="block-file-selection">
<p>
Selected files :
</p>
<div id="fileselect">
</div>
</div>
Jquery
var fileInput = document.getElementById('id_Filename');
var fileListDisplay = document.getElementById('fileselect');
var fileList = [];
var renderFileList, sendFile;
fileInput.addEventListener('change', function (evnt) {
fileList = [];
for (var i = 0; i < fileInput.files.length; i++) {
fileList.push(fileInput.files[i]);
}
renderFileList();
});
renderFileList = function () {
fileListDisplay.innerHTML = '';
fileList.forEach(function (file, index) {
var fileDisplayEl = document.createElement('p');
fileDisplayEl.innerHTML = `${file.name} <button data-index="${index}" class='deletfile'>X</button>`;
fileListDisplay.appendChild(fileDisplayEl);
});
};
$(document).on('click','.deletfile', function()
{
const index= $(this).attr('data-index');
fileList.splice(parseInt(index, 10), 1);
$(this).parent().remove();
});