七牛云上传: 使用 Ant Design Upload 组件

后台的上传 scope 是 bucket:key 形式的,所以在上传时 formData 的应该是下面的结构:

因此,我们需要给 Upload 这个组件传入 额外的 token、key. 根据官方文档,传入额外的参数只需要给它加上 data 这个属性就可以了,对应的值是一个 Object.
<Upload {…otherProps} data={{ token: ‘xxxx:token’, key: ‘xxx:key’ }} />
具体的代码如下:
import { Upload } from 'antd'
const uploadProps = {
action: `https://up-z2.qiniu.com`,
name: 'file',
listType: 'picture-card',
className: 'avatar-uploader'
}
class UploadImg extends Component {
state = {
token: null,
key: null,
domain: null,
loading: false,
}
componentDidMount() {
getImgUploadToken()
.then(({ token, key, domain }) => {
this.setState({
token,
key,
domain
})
})
}
handleAvatarChange = ({ file }) => {
if (file.status === 'uploading') {
this.setState({ loading: true })
return
}
if (file.status === 'done') {
const { response: { hash } } = file
const imageSrc = `${this.state.domain}${hash}`
updateProfilePic(imageSrc)
.then(() => {
console.log('上传成功')
})
}
}
render() {
const { token, key } = this.state
const {
user,
imageUrl,
form: { getFieldDecorator }
} = this.props
return (
<Upload {...uploadProps}
className={'profile-uploader'}
accept="image/*"
showUploadList={false}
data={{ token, key }}
beforeUpload={beforeUpload}
onChange={this.handleAvatarChange}>
<img src={imageUrl}
style={{
width: '102px',
height: '102px'
}}
alt="" />
</Upload>
)
}
}
export default UploadImg


