我目前正在使用 jQuery 和 PHP 创建一个图片上传页面。但是,我在代码中遇到了一些问题。当我选择多个文件上传时,代码会多次上传相同数量的文件。例如,如果我选择 2 个文件,它会上传这 2 个文件两次,如果我选择 3 个文件,它会上传这 3 个文件三次。
我还实现了一个 PHP 脚本来同时处理多个文件上传,但即使这样做了,问题仍然存在。此外,当我删除多个文件上传功能时,代码仅上传所选多个文件中的最后一个文件。
var files;
var currentFileIndex;
var isUploading = false; // Flag to check if a file is currently being uploaded
$('input[type="file"]').on('change', function (e) {
files = e.target.files;
currentFileIndex = 0;
uploadNextFile();
$('.uploadProgress').addClass('show');
});
function uploadNextFile() {
var progressBar = $('.js-upload-progress-bar');
var uploadForm = $('#uploadForm');
if (currentFileIndex < files.length) {
if (!isUploading) { // Check if a file is currently being uploaded
isUploading = true; // Set flag to true when starting to upload a file
var file = files[currentFileIndex];
var fileSize = file.size / (1024 * 1024); // File size in MB
var fileType = file.type;
var isImage = fileType.startsWith('image/');
var isVideo = fileType.startsWith('video/');
if (fileSize <= 1024 && (isImage || isVideo)) { // Validate file size and type
var previewSrc = isVideo ? '../assets/images/icons/icons-video.png' : URL.createObjectURL(file);
$('.js-previewImg').attr('src', previewSrc);
$('.js-uploadStatus').text('Uploading ' + (currentFileIndex + 1) + '/' + files.length); // Update upload status
var formData = new FormData(uploadForm[0]);
formData.set('file', file); // Set current file in FormData
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable) {
var progress = Math.round((e.loaded / e.total) * 100);
progressBar.val(progress);
}
});
return xhr;
},
success: function (response) {
console.log(response);
currentFileIndex++;
isUploading = false; // Reset flag when current file upload is completed
uploadNextFile(); // Upload next file after completing the current one
},
error: function (xhr, status, error) {
console.log('Error: ' + error);
currentFileIndex++;
isUploading = false; // Reset flag when current file upload is completed
uploadNextFile();
}
});
} else {
// File validation failed, show error
console.log('File validation failed');
currentFileIndex++;
isUploading = false; // Reset flag when current file upload is completed
uploadNextFile();
}
}
} else {
$('.js-uploadStatus').text('Upload Successful');
setTimeout(function() {
$('.uploadProgress').removeClass('show');
$('input[type="file"]').val(''); // Reset file input value
isUploading = false; // Reset flag when uploading is completed
}, 1000);
progressBar.val(0); // Reset progress bar
currentFileIndex = 0; // Reset current file index
}
}