Search code examples
reactjsfile-uploadantd

How to limit file upload and display message once in React with AntD?


I want to limit the number of files to be uploaded to 10 and display an error message if the number exceeds 10 only once. But I am getting the error message 11 times on my screen if I try to upload 11 files at once.

const beforeUpload = (file,fileList) => {
        const maxFileSize = 250 * 1024 * 1024; // 250MB limit
        const maxLimit = 10
        if (fileList.length>maxLimit){
            message.error(`Only 10 files allowed`);
            return false;
        }

        if (file.size > maxFileSize) {
            message.error(`${file.name} file upload failed (exceeds 250MB)`);
            console.error("File size exceeds the limit of 250MB");
            return false;
        }
        return true;
    };

I tried handling it in beforeUpload but I am able to disable file upload if it exceeds 10 files. However I am not able to display the message once. It gets displayed 11 times if I try to upload 11 files. Any ideas on how to display message once and limit file upload?

<Upload.Dragger multiple beforeUpload={beforeUpload} customRequest={handleFileUpload} showUploadlist={false}>...</Upload.Dragger>


Solution

  • The easest way to limit how many files can be uploaded at once is to use max count prop but in this case you'll not have your user notificated.

    If you need to notify the user you can use a ref to control if you've alread notificated your user about this error:

    const notificated = useRef(false)
    function beforeUpload(file){
      const index = fileList.indexOf(file);
      const maxLimit = 10
      if (fileList.length > maxLimit){
        if (!notificated.current) {
          notificated.current = true;
          message.error(`Only 10 files allowed`);
        }
    
        if (index === fileList.lenght - 1) {
          // reached last upload item
          // we must reset notification status now
          notificated.current = false;
        }
    
        return false;
      }
    
      const maxFileSize = 250 * 1024 * 1024; // 250MB limit
      if (file.size > maxFileSize) {
        message.error(`${file.name} file upload failed (exceeds 250MB)`);
        console.error("File size exceeds the limit of 250MB");
        return false;
      }
      return true;
    };
    

    You can also find a working example here