用表單上傳組件最痛苦的地方是:
他的諸多行為與純上傳組件不一樣,而表單的文檔關於這一塊基本上沒有提,只能自己試。
比如我想做一個上傳前的攔截。
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); })
通過這個方法,讓文件數組里只有一個文件對象。
再次上傳時,舊的會被新的頂掉。
以上。