尽管提供了接受道具,但 Antd 上传器仍接受所有文件 [英] Antd uploader accepting all files despite giving the accept prop
问题描述
我正在使用 antd 拖放组件 https://ant.设计/组件/上传/#components-upload-demo-drag.在他们给出的示例中,如果我添加 prop 接受它只接受受限制的格式,并且不会在 fileList 中添加其他文件.但是,当我在应用程序中使用此组件时,它会添加各种文件.为什么会出现这种行为以及如何避免?
I am using antd drag and drop component https://ant.design/components/upload/#components-upload-demo-drag. In the example they have given if I add the prop accept it only accepts the restricted formats and do not add other files in the fileList. However when I use this component in my application, it adds all kinds of files. Why is this behavior occuring and how to avoid it?
const Uploader = () => {
const [files, setFiles] = useState([])
const onChangeHandler = (res) => {
setFiles(res.fileList)
};
console.log(files)
return (
<Upload.Dragger
accept=".pdf,.doc,.docx"
onChange={onChangeHandler}
showUploadList={false}
multiple
fileList={files}
>
Upload
</Upload.Dragger>
);
};
例如,如果我拖动一个 png 图像,它不会添加到 fileList 中,但是如果我手动选择任何文件(不在接受属性中),它会添加我不想要的状态.有什么帮助吗?
If I drag a png image for instance it does not get added in the fileList but if I manually select any file (which is in not in accept prop) it adds in state which I do not want. Any help?
推荐答案
你可以结合道具 beforeUpload
(文档中的示例)
You can combine with the prop beforeUpload
(example in the documentation)
示例:
const Uploader = () => {
const types = ["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingm","application/msword"];
const [files, setFiles] = useState([])
const onChangeHandler = (res) => {
console.log(res);
let addFiles = true;
for(let i = 0; i < res.fileList.length; i++) {
if (!types.includes(res.fileList[i].type)) {
addFiles = false;
}
}
if( addFiles ) {
setFiles(res.fileList);
}
console.log(files);
};
return (
<Upload.Dragger
accept=".pdf,.doc,.docx"
beforeUpload={(file) => {
if (!types.includes(file.type)) {
message.error(`${file.name} is not a pdf, doc or docx file`);
return false;
} else {
return true
}
}}
onChange={onChangeHandler}
showUploadList={false}
multiple
fileList={files}
>
Upload
</Upload.Dragger>
);
};
这篇关于尽管提供了接受道具,但 Antd 上传器仍接受所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!