HTML
<a-upload
name="avatar"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
action="none"
:multiple="false"
:before-upload="beforeUpload"
:customRequest="customUpload"
>
<img v-if="form.url" :src="form.url" alt="avatar" />
<div v-else>
<a-icon :type="loading ? 'loading' : 'plus'" />
<div class="ant-upload-text"></div>
</div>
</a-upload>
JS
beforeUpload (file) {
this.loading = true
const BMP = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
this.$message.error('上传图片大小不能超过 2MB!')
return
}
if (!BMP) {
this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式!')
return
}
},
customUpload (e) {
let files = new FormData()
files.append('uploadFile', e.file)
this.$api.upload(files).then((res) => {
this.loading = false
if (res.errCode === '0') {
this.$message.success(res.errDesc)
this.form.url = res.result.url
}
}).catch(err => {
this.$message.success(err)
this.loading = false
})
}