antd實戰:表單上傳,文件列表的過濾與限制。


用表單上傳組件最痛苦的地方是:

他的諸多行為與純上傳組件不一樣,而表單的文檔關於這一塊基本上沒有提,只能自己試。

 

比如我想做一個上傳前的攔截。

beforeUpload: (file, fileList) => {
      const isJpgOrPng =
        file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isJpgOrPng) {
        message.error('您只能上傳JPG或PNG圖片');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        message.error('您的圖片大於10M,請重新上傳');
        return false;
      }
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        this.setState({
          logoUrl: reader.result,
        });
      };
    },

這個代碼在一般的上傳是有效的,但是表單上傳就不行。

因為,就算你 return false 了,這個文件還是會進文件列表!

 

所以只能在包裹上傳組件的表單組件上動腦子了。

HTML:

<FormItem>
                    {getFieldDecorator(`upload_logo`, {
                      initialValue: undefined,
                      valuePropName: 'fileList',
                      getValueFromEvent: this.normFile,
                    })(
                      <Upload {...this.uploadLogoProps}>
                        <div
                          className={styles.logoBtn}
                          style={{ cursor: 'pointer' }}
                        ><button>
                              點擊上傳圖片
                              <div className={styles.pos}>
                                <Icon type="plus" />
                              </div>
                            </button></div>
                      </Upload>,
                    )}
                  </FormItem>

JS:

// 上傳控件用方法 LOGO
  // 項目照片只需要 1 個
  normFile = e => {
    let limit = 1;
    if (Array.isArray(e)) {
      return e;
    }
    return (
      e &&
      e.fileList &&
      e.fileList
        .filter((item, index, arr) => {
          return !!item.status;
        })
        .filter((item, index, arr) => {
          return index > arr.length - (limit + 1);
        })
    );
  };

通過 status 的判斷把沒有上傳的文件過濾掉。

 

另外這個代碼還做了另外一件事:

.filter((item, index, arr) => {
          return index > arr.length - (limit + 1);
        })

通過這個方法,讓文件數組里只有一個文件對象。

再次上傳時,舊的會被新的頂掉。

 

以上。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM