做了個antd的上傳簡單封裝,很煩。主要用的方法就是使用customRequest 這個覆蓋上傳組件的默認上傳,實現自定義上傳。有的地方可能比較low 因爲我不知道其他方法。。
import React from 'react'
import { Icon, Button, Upload } from 'antd';
import { uploadimg } from '../../api/login' // 封裝的上傳路徑
export default class FileUpload extends React.Component {
constructor(props) {
super(props)
this.state = {
fileList: []
}
this.removeFile = this.removeFile.bind(this)
}
removeFile(file){
console.log(file)
this.state.fileList.map((v,i)=>{
if(file.uid === v.uid){
this.state.fileList.splice(i,1)
this.setState({fileList:this.state.fileList})
this.props.onChange(this.state.fileList)
}
})
}
customRequest = (option) => {
var that = this
const formData = new FormData();
formData.append('photo', option.file);
uploadimg(formData).then(res => {
console.log(res)
this.state.fileList.push({
name: 'yyy.png',
status: 'done',
url: res.data[0].file_url,
})
this.state.fileList.map((v, i) => {
v.uid = i
})
this.setState({
fileList: this.state.fileList
})
this.props.onChange(this.state.fileList)
})
}
render() {
const fileList = this.state.fileList
return (
<Upload
// accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
customRequest={this.customRequest}
// beforeUpload={this.beforeUpload}
onRemove = {this.removeFile}
fileList={fileList}
>
<Button>
<Icon type='upload' />上傳
</Button>
</Upload>
)
}
}
下面的是antd 上傳與form結合使用的方法,這個我在網上找了好久都沒找到。。。。。
這個就是在你的form表單放入這個item 然後點擊確定就有數據了rules自己設定吧我隨便寫的。
<Form.Item {...formItemLayout} label="遊戲應用">
{getFieldDecorator('upload', {
valuePropName: 'gamefileList',
getValueFromEvent: this.handlePhotoChange,
rules: [
{
required: true, message: 'Please input your note!'
}
],
})(
<FileUpload onChange={this.handlePhotoChange} />
)}
</Form.Item>