我有一個文件上傳器,它為要上傳的文件提供預覽圖像。有前端和后端驗證,可防止在一次上傳中提交超過10個文件。
我想做的是,當附加了10個以上的文件時,第10個以上圖像的預覽圖像將從圖像預覽中刪除(當前也有錯誤消息輸出)。對于輸入元素中的實際FileList文件,我有單獨的功能,但應該能夠使解決方案同時適用于這兩個元素。
下面是問題的最小代碼表示。如果需要,我可以顯示完整的文件上傳器代碼,但有相當多的代碼與此問題無關(guān),這可能會讓人困惑。
// Generate a preview <img> for each selected file
// the submitData.files array is generated from a change event listener on a file input elment
[...submitData.files].forEach(showFiles);
});
function showFiles(file) {
let previewImage = new Image();
previewImage.className = "img upload-preview-image";
previewImage.src = URL.createObjectURL(file);
// use decode() method that waits for individual preview images to be added when running validations
previewImage.decode().then((response) => {
// validations happen here for each image as part of the showFiles() function called in the forEach loop above
let imgList = document.querySelectorAll('.upload-preview-image'), // redeclare under new var name inside promise
if (imgList.length > 10) {
/*** somehow remove all images from the imgList array after the 10th image,
either by deleting them or exiting this function when the 10th item is added ***/
}
}).catch((encodingError) => {
// Do something with the error.
});
}
如果您只想處理輸入中的前10個文件,那么可以將它們從
submitData.files
數(shù)組中切掉: