英文:
JS - Check *all* selected files on dragenter, error if any do not meet requirement
问题
I have a drag and drop image "uploader" (it does not upload, only converts to base64 and displays thumbnails). Currently if you drag one file into the dropzone, if it is not a .jpg/.jpeg it will show error (this is correct functionality), but if you drag multiple files into the dropzone, it does not show the error if at least 1 file is a jpg, even if the other file(s) do not meet jpg requirement, which is not what should happen (ex: you select .jpg and .zip, this will not trigger error, but it should). I need to show the error always unless all selected files are .jpg. Can anyone assist?
Here is the relevant dragenter code (same code for dragover)
container.addEventListener(
"dragenter",
(e) => {
e.preventDefault();
e.stopPropagation();
const img = Array.from(e.dataTransfer.items).find(e => e.type.match('image/jpeg'))
if (img){
container.classList.add("active");
}else{
error.innerHTML = "HTML removed from snippet for readability";
error.classList.remove("hideit");}
},
false
);
You can view the code here: https://jsfiddle.net/x2fyrcLb/2/
英文:
I have a drag and drop image "uploader" (it does not upload, only converts to base64 and displays thumbnails). Currently if you drag one file into the dropzone, if it is not a .jpg/.jpeg it will show error (this is correct functionality), but if you drag multiple files into the dropzone, it does not show the error if at least 1 file is a jpg, even if the other file(s) do not meet jpg requirement, which is not what should happen (ex: you select .jpg and .zip, this will not trigger error, but it should). I need to show the error always unless all selected files are .jpg. Can anyone assist?
Here is the relevant dragenter code (same code for dragover)
container.addEventListener(
"dragenter",
(e) => {
e.preventDefault();
e.stopPropagation();
const img = Array.from(e.dataTransfer.items).find(e => e.type.match('image/jpeg'))
if (img){
container.classList.add("active");
}else{
error.innerHTML = "HTML removed from snippet for readability";
error.classList.remove("hideit");}
},
false
);
答案1
得分: 1
尝试将“find
”更改为“every
”(搜索 MDN 文档以查找“Array.prototype.every
”):
const img = Array.from(e.dataTransfer.items).every(e => e.type.match('image/jpeg'))
还有另一种数组方法,some
,用于检查“如果至少有一个”。
英文:
Try changing "find
" to "every
" (search MDN documentation for "Array.prototype.every
"):
const img = Array.from(e.dataTransfer.items).every(e => e.type.match('image/jpeg'))
There's another array method, some
, for checking "if at least one".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论