好久沒更博客了......這他麼活根本幹不完我有啥辦法啊o(╥﹏╥)o
直接進入正題:
思路:首先,當調用Upload組件的時候每次選擇後會自動上傳而不會隨表單一起提交,這個顯然不符合實際需求,所以需要在Upload組件中定義beforeUpload方法並且返回false攔截文件的自動上傳,同時把文件信息添加到state中,此時需要考慮到對於上傳列表的刪除對state的影響,所以需要在Upload組件中添加onRemove方法用於在刪除列表時候實時更新state,根據此思路得出的代碼如下:
//這個是監聽文件變化的
fileChange=(params)=>{
const {file,fileList}=params;
if(file.status==='uploading'){
setTimeout(()=>{
this.setState({
percent:fileList.percent
})
},1000)
}
}
// 攔截文件上傳
beforeUploadHandle=(file)=>{
this.setState(({fileData})=>({
fileData:[...fileData,file],
}))
return false;
}
// 文件列表的刪除
fileRemove=(file)=>{
this.setState(({fileData})=>{
const index=fileData.indexOf(file);
const newFileList=fileData.slice();
newFileList=splice(index,1);
return {
fileData:newFileList
}
})
}
.
.
.
.
render(){
<FormItem labelCol={{span:5}} wrapperCol={{span:15}} label='文件上傳'>
{getFieldDecorator(form,settings,formName,'name',values)(
<Upload action='路徑' beforUpload={this.beforeUploadHandle} onChange={this.fileChange} onRemove={this.fileRemove} fileList={this.state.fileData}>
<Button><Icon type='upload' />上傳文件</Button>
</Upload>
)}
</FormItem>
}
到這個時候關於文件處理的部分已經基本完成,接下來就是講文件信息和其他表單信息一起提交,這個時候需要用到formData();通過append方法將數據逐條添加到formData中(tips:formData數據在console後只有一個空的對象,但是數據都在裏面,要想獲取數據需要調用formData.get()方法);此部分的代碼爲:
const {fileData}=this.state;
const formData=new formData();
fileData.forEach((file)=>{
formData.append('files',file);
})
// fields爲表單其他項的數據,在antd-pro中是fileds.f
Object.keys(fields).map((item)=>{
formData.append(item,fields[item]);
})
this.props.dispatch({
type:'pluginInfo/upload',
payload:formData,
callback:()=>{
resetFields();
this.setState({
fileData:[],
})
this.props.handleModalVisible(false)//這個是項目中的關閉彈窗方法,可以無視
}
})
到了此時你的表單數據以及文件信息已經全部發送給了後臺
結語:那個攔截文件上傳的你可以在antd的官網中看到完整的例子,因爲代碼在公司的內網上,這些代碼都是自己一個一個碼出 來的,如果對各位有幫助的話,麻煩點個贊支持一下,謝謝了。(*^▽^*)