vue+elementUI中使用el-upload进行图片上传
  VHT3PPYyRwqf 2023年11月02日 88 0


<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进行图片上传_上传


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
VHT3PPYyRwqf