Removing file from multiple files uploader on button click when using HTML5 file input
The file list of HTML5 file input is readonly, so when trying to remove a file from it you won't be allowed.
What you need to do is maintain a separate array list (JSON array as per the example).
I have wrapped your X button with a div that hold the file index concatenated to a 'file_' string, and added an onclick
function removeLine(obj)
that accepts the element as an object.
I have also added a JSON array finalFiles
in the global scope as well as moved the inputFile
to the global scope.
When the file input changes, I am setting the JSON array with the selected files through :
$.each(this.files,function(idx,elm){
finalFiles[idx]=elm;
});
The function removeLine
will flush the input file list to allow the same file selection again if the user removed the file by mistake, the function obtains the file index from the wrapper division id, removes the wrapper div then deletes the file from the JSON array.
function removeLine(obj)
{
inputFile.val('');
var jqObj = $(obj);
var container = jqObj.closest('div');
var index = container.attr("id").split('_')[1];
container.remove();
delete finalFiles[index];
//console.log(finalFiles);
}
You can the maintain your files when the form submits and send them through AJAX post using FormData in a similar manner to This Article.
var dropZoneId = "drop-zone"; var buttonId = "clickHere"; var mouseOverClass = "mouse-over";var dropZone = $("#" + dropZoneId); var inputFile = dropZone.find("input"); var finalFiles = {};$(function() {
var ooleft = dropZone.offset().left; var ooright = dropZone.outerWidth() + ooleft; var ootop = dropZone.offset().top; var oobottom = dropZone.outerHeight() + ootop; document.getElementById(dropZoneId).addEventListener("dragover", function(e) { e.preventDefault(); e.stopPropagation(); dropZone.addClass(mouseOverClass); var x = e.pageX; var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) { inputFile.offset({ top: y - 15, left: x - 100 }); } else { inputFile.offset({ top: -400, left: -400 }); }
}, true);
if (buttonId != "") { var clickZone = $("#" + buttonId);
var oleft = clickZone.offset().left; var oright = clickZone.outerWidth() + oleft; var otop = clickZone.offset().top; var obottom = clickZone.outerHeight() + otop;
$("#" + buttonId).mousemove(function(e) { var x = e.pageX; var y = e.pageY; if (!(x < oleft || x > oright || y < otop || y > obottom)) { inputFile.offset({ top: y - 15, left: x - 160 }); } else { inputFile.offset({ top: -400, left: -400 }); } }); }
document.getElementById(dropZoneId).addEventListener("drop", function(e) { $("#" + dropZoneId).removeClass(mouseOverClass); }, true);
inputFile.on('change', function(e) { finalFiles = {}; $('#filename').html(""); var fileNum = this.files.length, initial = 0, counter = 0;
$.each(this.files,function(idx,elm){ finalFiles[idx]=elm; });
for (initial; initial < fileNum; initial++) { counter = counter + 1; $('#filename').append('<div id="file_'+ initial +'"><span class="fa-stack fa-lg"><i class="fa fa-file fa-stack-1x "></i><strong class="fa-stack-1x" style="color:#FFF; font-size:12px; margin-top:2px;">' + counter + '</strong></span> ' + this.files[initial].name + ' <span class="fa fa-times-circle fa-lg closeBtn" onclick="removeLine(this)" title="remove"></span></div>'); } });
})
function removeLine(obj){ inputFile.val(''); var jqObj = $(obj); var container = jqObj.closest('div'); var index = container.attr("id").split('_')[1]; container.remove();
delete finalFiles[index]; //console.log(finalFiles);}
#drop-zone { width: 100%; min-height: 150px; border: 3px dashed rgba(0, 0, 0, .3); border-radius: 5px; font-family: Arial; text-align: center; position: relative; font-size: 20px; color: #7E7E7E;}#drop-zone input { position: absolute; cursor: pointer; left: 0px; top: 0px; opacity: 0;}/*Important*/
#drop-zone.mouse-over { border: 3px dashed rgba(0, 0, 0, .3); color: #7E7E7E;}/*If you dont want the button*/
#clickHere { display: inline-block; cursor: pointer; color: white; font-size: 17px; width: 150px; border-radius: 4px; background-color: #4679BD; padding: 10px;}#clickHere:hover { background-color: #376199;}#filename { margin-top: 10px; margin-bottom: 10px; font-size: 14px; line-height: 1.5em;}.file-preview { background: #ccc; border: 5px solid #fff; box-shadow: 0 0 4px rgba(0, 0, 0, 0.5); display: inline-block; width: 60px; height: 60px; text-align: center; font-size: 14px; margin-top: 5px;}.closeBtn:hover { color: red; display:inline-block;}}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><div id="drop-zone"> <p>Drop files here...</p> <div id="clickHere">or click here.. <i class="fa fa-upload"></i> <input type="file" name="file" id="file" multiple /> </div> <div id='filename'></div></div>
how to remove a file from file upload control before uploading it using jQuery
From your code, I can see that you forget to remove the dom that why the file still exists.
Another, to make the code simple we can attach data-index
inside the delete button to remember the file index when we're deleting it will be easy than compare the string of filename.
Here is the modified code.
var fileInput = document.getElementById('inputfile');
var fileListDisplay = document.getElementById('allfiles');
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();
});
Multiple file upload - with 'remove file' link
As in this JSFiddle, I've added a class name .removeFile
to the dynamically generated remove
link; then use this class as a selector to pick up the one which is clicked and remove the parent li
.
Updated:
JS:
// add .removeFile class to the li's element to pick them by this selector
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name), "</strong> - ",
f.size, " bytes. ", removeLink, "</li> ");
}
$(this).children(".fileList")
.append(output.join(""));
});
};
var filesToUpload = [];
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
//console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
//console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
You can un-comment the console.log() statements to see the result
Related Topics
How to Reload a Page With React-Router
How to Get Only 1St Element of Json Data
Loading Screen Gets Stuck While Processing Http Request
Regex in JavaScript Allow Only Numbers and One Dot Followed by Max 2 Number
How to Show Which Question a User Is on When Taking My Quiz
Regex for Names Validation Allow Only Letters and Spaces
Check If Page Gets Reloaded or Refreshed in JavaScript
How to Add Multiple Values in Json Object and Get an Updated Json File
How to Get the Name of the Current Windows User in JavaScript
Regex to Replace Everything Except Numbers and a Decimal Point
Foreach Is Not a Function Error With JavaScript Array
How to Pass the Checked and Unchecked Value of Checkboxes in Component.Ts File in Angular
How to Find Middle Element of Array in JavaScript
Convert JavaScript Date Format to Yyyy-Mm-Ddthh:Mm:Ss
Safari Browser Audio.Play() Is Not Working
How to Display an Image from an Array of Images in React