I am trying to display the details of multiple uploaded files using jQuery.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Multi File Upload</title>
</head>
<body>
<form id="file_upload" action="" method="get" enctype="multipart/form-data">
<p><input type="file" name="file_1" class="uploadFile"></p>
<p>
<input type="submit" value="Upload" id="btnSubmit">
<a id="add_more" href="#">Add more</a>
</p>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#add_more").click(function(){
var current_count = $("input[type='file']").length;
var next_count = current_count + 1;
$("#file_upload").prepend('<p><input type="file" name="file_'+next_count+'" class="uploadFile" /></p>');
});
$("#btnSubmit").click(function(e){
e.preventDefault();
var file_count = $(".uploadFile").length;
var file_arr = [];
for (var i = 0; i < file_count; i++){
// file_arr[i] = $(".uploadFile")[i].files[i];
file_arr[i] = $(".uploadFile").prop('files')[i];
alert(file_arr[i].name);
alert(file_arr[i].size);
alert(file_arr[i].type);
}
});
});
</script>
</body>
</html>
But the problem is that it is displaying the details of the first uploaded file properly, and gives me error Uncaught TypeError: Cannot read property 'name' of undefined
for the 2nd file onward.
$("#btnSubmit").on('click', function () {
var fp = $(".uploadFile");
var lg = fp[0].files.length; // get length
var items = fp[0].files;
var fragment = "";
if (lg > 0) {
for (var i = 0; i < lg; i++) {
var fileName = items[i].name; // get file name
var fileSize = items[i].size; // get file size
var fileType = items[i].type; // get file type
// append li to UL tag to display File info
fragment += "<li>" + fileName + " (<b>" + fileSize + "</b> bytes) - Type :" + fileType + "</li>";
}
$("#ulList").append(fragment);
}
});