el-upload图片上传前端压缩(auto-upload版本)

标签中添加before-upload的hock

	<el-upload
	  class="avatar-uploader"
	  :action="baseUrl + '/v1/addimg/shop'"
	  :show-file-list="false"
	  :on-success="handleShopAvatarScucess"
	  :before-upload="beforeAvatarUpload">
	</el-upload>

hock方法
beforeAvatarUpload (file) { 
	return new Promise((resolve, reject) => {
		imageConversion.compressAccurately(file, 40).then(res => { 
			var compressed_file = new File([res], file.name, {type: file.type, lastModified: Date.now()});
			compressed_file.uid = file.uid;
			resolve(compressed_file)
		})
	})
}, 

上面的添加好就ok了,接下来看下源码

网上很多版本都是使用submit时才上传的,而直接使用auto-upload上传时的情况没有考虑到,而在源码中还是有些区别的

upload(rawFile, file) {
      this.$refs.input.value = null;

      if (!this.beforeUpload) {
        return this.post(rawFile);
      }

      const before = this.beforeUpload(rawFile);
      if (before && before.then) {
        before.then(processedFile => {
        
          //进行了判断,此处需要将blob对象转化为object
          if (Object.prototype.toString.call(processedFile) === '[object File]') {
          
            this.post(processedFile);  // 这里进入
          } else {
            this.post(rawFile);
          }
        }, () => {
          this.onRemove(null, rawFile);
        });
      } else if (before !== false) {
        this.post(rawFile);
      } else {
        this.onRemove(null, rawFile);
      }
    },
post(rawFile) {
      const { uid } = rawFile;
      const options = {
 
        onProgress: e => {
          this.onProgress(e, rawFile);    //继续进入
        },
        onSuccess: res => {
        },
        onError: err => {
        }
      };
    },
 handleProgress: function handleProgress(ev, rawFile) {
	      var file = this.getFile(rawFile);          //这里进去
	      this.onProgress(ev, file, this.uploadFiles);
	      file.status = 'uploading';
	      file.percentage = ev.percent || 0;
	    },
getFile: function getFile(rawFile) {
	      var fileList = this.uploadFiles;
	      var target = void 0;
	      fileList.every(function (item) {
	      
	      //这里进行了判断,file的uid是否相等,所以需要将原来file等uid复制过来
	        target = rawFile.uid === item.uid ? item : null;   
	        return !target;
	      });
	      return target;
	    },
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值