引入
import {Upload, } from 'antd';
import { connect } from 'dva'
import shortid from 'shortid'//生成唯一id
// [] 指针 123
const [fileList, setFileList] = useState([]) // 上传缩略图列表
上传方法调用
const onBeforeUpload = file => {
const {
type, // 文件类型
size, // 文件大小 字节
} = file
if (type !== 'image/png') {
console.log('图片格式不对');
return false
}
if (fileList.length > 3) {
console.log('最多上传4张');
return false
}
const formData = new FormData()
formData.append('file', file)
dispatch({
type: 'join/fetchUpload',
payload: formData
})
.then(res => {
if (res) {
fileList.push({
uid: shortid.generate(), // uid 必须唯一
name: 'image.png',
status: 'done',
url: res,
})
setFileList([...fileList])
}
})
return false
}
// 单张
const onRemove = file => {
setFileList(fileList.filter(dt => dt.uid !== file.uid))
}
和ant的form连用
<Form.Item
label="上传图片"
>
<Upload
name="logo"
fileList={fileList} // fileList 展示上传缩略图列表
beforeUpload={onBeforeUpload} // 上传之前的钩子
onRemove={onRemove} // 删除事件
listType="picture-card"
>
<Button>上传</Button>
</Upload>
</Form.Item>
请求
// 上传
*fetchUpload({ payload }, { call, put, select }) {
const res = yield call(() => api.getUpload(payload));
if (!res.code) {
return res.result;
}
},