表格删除同名文件后无法重新上传的技术问题求助
问题:删除文件后无法直接重新上传同名文件
上传x.png后将其删除,无法直接重新上传该文件;但先上传其他文件(如z.png)后,就能再次上传x.png。
原因
这是因为浏览器的文件输入框(<input type="file">)默认不会触发onchange事件,当用户选择和上次完全相同的文件时。浏览器判断文件选择没有变化,所以不会执行handleFiles函数,自然不会重新添加文件到表格里。
当你先上传z.png时,文件输入框的选中内容发生了改变,再选x.png时,浏览器会认为是新的选择,才会触发onchange事件。
解决方案
方法1:处理完文件后清空输入框
在handleFiles函数执行完毕后,手动清空文件输入框的value,这样每次选择文件(包括同名文件)都会触发onchange事件。
修改handleFiles函数,在末尾添加清空代码:
function handleFiles(files) { const tbody = document.querySelector(".files-table tbody"); for (const file of files) { const fileName = file.name; const isDuplicate = Array.from(tbody.rows).some( (row) => row.cells[0].textContent === fileName ); if (!isDuplicate) { const row = tbody.insertRow(); const filenameCell = row.insertCell(0); const typeCell = row.insertCell(1); const statusCell = row.insertCell(2); const dateCell = row.insertCell(3); const deleteCell = row.insertCell(4); filenameCell.textContent = fileName; typeCell.textContent = getFileType(file.type); statusCell.textContent = "Pending"; const currentDate = new Date(); const formattedDate = currentDate.toISOString().split("T")[0]; dateCell.textContent = formattedDate; // Only the date // Add delete icon to the last cell const deleteIcon = document.createElement("i"); deleteIcon.className = "fa-regular fa-trash-can"; deleteIcon.style.color = "#d90000"; deleteIcon.addEventListener("click", function () { deleteRow(this); }); deleteCell.appendChild(deleteIcon); } } checkIconVisibility(); // 清空文件输入框,确保下次选择同名文件能触发onchange document.getElementById('tableFiles').value = ''; }
方法2:点击按钮时重置输入框
给"Add Files"按钮绑定点击事件,每次点击时先清空输入框:
document.querySelector('.choose-file-btn').addEventListener('click', function() { document.getElementById('tableFiles').value = ''; });
这样用户每次点击按钮时,输入框都会被重置,选择同名文件也能正常触发onchange事件。
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

