1 回答
TA贡献1877条经验 获得超1个赞
您需要initially使用函数将所有文件存储在一个数组中change,然后将删除图标 HTML 数据存储在另一个数组中,以匹配fileName我们当前在主filesToUpload数组中的 和 id。
如果文件名与fileName我们当前的匹配filesToUpload,我们只需从主数组和removeFile数组中拼接该项目即可。
要append关闭文件icon和文件,data我们可以检查数组的长度removeFile,然后使用函数附加数据.join()。
我还添加了一个实时计数器。从数组中删除文件后检查剩余的文件数量filesToUpload。
此外,如果您单击按钮,Upload您将看到需要controller以.processingformData
现场演示:(我也为每一行添加了注释供您参考)
$(document).ready(function(readyEvent) {
var filesToUpload = []; //store files
var removeFile = []; //remove remove files
var fileCounter = 0; //count files
//upload file
$('#upload_requiremnt_files').on('change', function() {
$("#upload_prev").html('');
fileCounter = this.files.length; //count files
//Store all files to our main array
var files = this.files;
for (var i = 0; i < files.length; i++) {
filesToUpload.push(files[i]);
}
//Push file to remove file to that we can match to remove file
for (var i = 0, f; f = files[i]; i++) {
removeFile.push('<div class="filenameupload" id="' + i + '" fileName="' + f.name + '" >' + f.name + '<p class="close" ><i class="fa fa-window-close" aria-hidden="true"></i></p></div>');
}
//Append Remove file icon to each file
if (removeFile.length) {
$("#upload_prev").html(removeFile.join(""));
}
//Show counter
$('#upload_count').show().text('Total Files To Upload = ' + fileCounter)
});
//Remove files
$(document).on('click', '.close', function() {
var i = $(this).parent().attr("id"); //get index
var fileName = $(this).parent().attr("fileName"); //get fileName
//Loop through all the file and remove Files
for (i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].name == fileName) {
//Remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
removeFile.splice(i, 1);
}
}
//Remove file from DOM
$(this).parent().remove();
//Decrease counter
fileCounter--
//Update counter
if (fileCounter > 0) {
$('#upload_count').text('Total Files To Upload = ' + fileCounter)
} else {
$('#upload_count').hide()
}
})
//Demo Upload button
$(document).on('click', '#upload_file', function() {
if (filesToUpload.length) {
alert(filesToUpload.length + ' files will be sent to controller')
} else {
alert('Nothing to upload')
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<input type="file" id="upload_requiremnt_files" name="upload_requiremnt_files[]" multiple>
<div id="upload_count"></div>
<div id="upload_prev"></div>
<br>
<button id="upload_file">Upload</button>
- 1 回答
- 0 关注
- 95 浏览
添加回答
举报