Home > other >  Antd file upload validation in Reactjs
Antd file upload validation in Reactjs

Time:04-15

I am having a file upload using Edit antd upload component as file selector (forked)

Result:

enter image description here

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).

Edit antd typescript (forked)

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>
  );
};

Edit antd-file-upload-validation-in-reactjs

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. enter image description here

Hope this solve your problem

  • Related