效果图:
html代码:
<a-upload
name="avatar"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
:before-upload="beforeUpload"
@change="imageUpload"
>
<img
v-if="imageUrl"
:src="imageUrl"
alt="avatar"
style="height:250px;width:250px;border-radius: 50%;"
/>
<div v-else>
<a-icon :type="loading ? 'loading' : 'plus'" />
<div class="ant-upload-text">
浏览
</div>
</div>
</a-upload>
js代码
<script>
function getBase64(img, callback) {
const reader = new FileReader()
reader.addEventListener('load', () => callback(reader.result))
reader.readAsDataURL(img)
}
export default {
data(){
return{}}}
methods:{
beforeUpload(file) {
console.log(file)
const isJpgOrPng =
file.type === 'image/jpeg' ||
file.type === 'image/png' ||
file.type === 'image/gif' ||
file.type === 'image/jpg'
if (!isJpgOrPng) {
return this.$message.error('请上传正确的图片格式!')
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
return this.$message.error('图片大小必须小于2MB!')
}
},
// 图片上传
async imageUpload(info) {
console.log(info)
if (info.file.status !== 'uploading') {
let file = new FormData()
file.append('file', info.file.originFileObj)
const { data: res } = await uploadImg(file)
if (res.code == 200) {
this.addForm.img_path = res.message
}
}
if (info.file.status === 'done') {
getBase64(info.file.originFileObj, imageUrl => {
this.imageUrl = imageUrl
console.log(this.imageUrl)
this.loading = false
})
this.$message.success(`${info.file.name} file uploaded successfully`)
} /* else if (info.file.status === 'error') {
this.$message.error(`${info.file.name} file upload failed.`)
} */
getBase64(info.file.originFileObj, imageUrl => {
this.imageUrl = imageUrl
// console.log(this.imageUrl)
this.loading = false
})
console.log(info)
},
}
</script>
详细见:Ant Design Vue