尽管提供了接受道具,但Antd上传器仍接受所有文件 [英] Antd uploader accepting all files despite giving the accept prop
问题描述
我正在使用antd拖放组件 https://ant.design/components/upload/#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
( 示例:
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屋!