Antd uploader accepting all files despite giving the accept prop

Viewed 1334

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

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?

1 Answers

You can combine with the prop beforeUpload (example in the documentation)

Example:

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