vue+elementUI中使用el-upload进行图片上传

<el-upload
     class="avatar-uploader" 
     action
     :show-file-list="false"
     :http-request="selectPicUpload"
     :before-upload="beforeAvatarUpload"
     :on-remove="handleRemove"
   >
     <img v-if="imageUrl" width="200px" height="200px" :src="imageUrl" class="avatar" />
     <i v-else class="el-icon-plus avatar-uploader-icon"></i>
 </el-upload>

代码解析:

action:必选参数,上传的地址/也可以为空掉接口写地址
show-file-list:是否显示已上传文件列表
http-request :覆盖默认的上传行为,可以自定义上传的实现
before-upload:绑定的是上传图片前要执行的方法用来限制图片的大小、格式
on-remove: 文件列表移除文件时的钩子
img 标签里放的是上传成功后显示出来的图片
i 标签里 放的是默认未上传图片时的图标

js代码:

//上传图标事件
    selectPicUpload(obj) {
      let fd = new FormData(); //参数的格式是formData格式的
      fd.append("file", obj.file); //参数
      this.$axios.postFile(this.$api.upload_photo, fd).then(res => {
        this.imageUrl = res.data.url;
        // this.backgroundUrl = res.data.backgroundUrl;
      });
    },

//对上传图片的大小、格式进行限制
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isJPG2 = file.type === "image/jpg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG && !isJPG2 && !isPNG) {
        this.$message.warning("只支持jpg或png格式图片");
      }
      if (!isLt5M) {
        this.$message.warning("请上传5MB以内的图片!");
      }
      return (isJPG || isJPG2 || isPNG) && isLt5M;
    },

// 移除图片方法

handleRemove(file) {
      this.imageUrl = "";
      this.backgroundUrl = "";
},

效果如下:

在这里插入图片描述
转载于 vue+elementUI中使用el-upload进行图片上传

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值