Element组件中upload上传图片
图示:
<template>
<div class="text-item">
<el-upload
class="avatar-uploader"
action="http://xxx/bo/upload"
<!--action 必选参数,上传的地址
show-file-list 是否显示已上传文件列表 -->
:show-file-list="false"
:on-success="onSuccessFile"
:before-upload="beforeAvatarUpload">
<el-avatar
:src="avatarUrl"
:size="102"
>
</el-avatar>
<!--el-avatar:头像标签 -->
</el-upload>
</div>
</template>
<script>
export default {
data(){
return{
avatarUrl:'https://el-admin.xin/avatar/avatar.jpeg',
imageUrl:'',
}
},
methods:{
<!-- on-success 文件上传成功时的钩子 function(response, file, fileList) -->
onSuccessFile(response,file,fileList){
if(response.code=='200'){
this.avatarUrl='http://xxx'+response.data
}
},
//上传头像
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
beforeAvatarUpload(file) {
console.log(file)
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 20;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
},
}
</script>