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 關注
- 160 瀏覽
添加回答
舉報