I am having a file upload using
Result:
After some try, I have prevented the file to display in the list if it is not valid but unfortunately the delete of the uploaded file doesn't work now (which was working fine before this current implementation).
CodePudding user response:
I was able to get the removal of selected/uploaded files by implementing an onRemove
handler.
Example:
const Uploader = () => {
const [fileList, setFileList] = useState<UploadFile[]>([]);
const validateFileType = (
{ type, name }: UploadFile,
allowedTypes?: string
) => {
if (!allowedTypes) {
return true;
}
if (type) {
return allowedTypes.includes(type);
}
};
const uploadProps = useMemo(
() => ({
beforeUpload: (file: UploadFile) => {
const isAllowedType = validateFileType(file, "image/png");
if (!isAllowedType) {
setFileList((state) => [...state]);
message.error(`${file.name} is not PNG file`);
return false;
}
setFileList((state) => [...state, file]);
return false;
},
onRemove: (file: UploadFile) => {
if (fileList.some((item) => item.uid === file.uid)) {
setFileList((fileList) =>
fileList.filter((item) => item.uid !== file.uid)
);
return true;
}
return false;
}
}),
[fileList]
);
return (
<Upload multiple {...uploadProps} fileList={fileList}>
<Button icon={<UploadOutlined />}>Upload png only</Button>
</Upload>
);
};
CodePudding user response:
You can create a state & control the fileList. In new version, we can use Upload.LIST_IGNORE but have a look at the API Section
. If you do not want to upload the file, you can simply return false or if you use promise, you can reject with reject(false)
.
Have a look at beforeUpload
in API Section of Upload Component.
Hope this solve your problem