vue+element实现图片上传

<el-upload
:action='接口路径'
:show-file-list='false'
name='img' //接口需要传的图片字段 可以直接在这定义
:with-credentials='true  //支持发送 cookie 凭证信息
:on-success='handleAvatarSuccess'
:before-upload='beforeAvatarUpload'
>
<img v-if='imageUrl' :src='imageUrl'/> //这里渲染根据接口拿到的图片路径 需在data中定义imageUrl
<i v-else class='elicon-plus avatar-uploader-icon'></i>
</el-upload>
handleAvatarSuccess(res){
    if(res.code==1){ //这里根据接口返回的去判断
        this.imageUrl = res.data.img_path  //拿到图片的路径
    }
}    

//限制上传时的文件格式大小
 beforeAvatarUpload(file) {
   const isJPG = file.type === "image/jpeg" || file.type === "image/png";
   const isLt2M = file.size / 1024 / 1024 < 3;
   if (!isJPG) {
     this.$message.error("上传图片只能是 JPG 和 Png 格式!");
     return false;
   }
   if (!isLt2M) {
     this.$message.error("上传图片大小不能超过 3MB!");
     return false;
   }
 },

 

猜你喜欢

转载自www.cnblogs.com/ccyq/p/13201644.html