element ui上传图片前端压缩

<el-upload action="$globalData.file.uploadUrl" :http-request="httpRequest" ref="_upload" class="upload-demo"
      :accept="accept" :limit="limit" :on-exceed="handleExceed" :before-upload="handleBeforeUpload"
      :on-error="handleError" :on-success="handleSuccess" :on-change="handleChange" :on-progress="handleProgress"
      :show-file-list="false" :file-list="uploadList" :disabled="uploadList.length >= limit" multiple>
      <el-button class="wp-button wp-btn-icon" icon="icon-shanchuan" type="primary"
        :disabled="uploadList.length >= limit">上传资料</el-button>
    </el-upload>
async httpRequest (option) {
      let fd = new FormData(); //参数的格式是formData格式的
      fd.append("file", option.file); //参数
      try {
        let res = await uploadFile(fd)
        if (Number(res.returnCode) !== 200) {
          // 清除 正在上传的文件中
          this.uploadList.splice(this.uploadList.indexOf(option.file), 1);
          return 
        }
        let file = res.returnData
        if (this.fileList.length < this.limit) {
          this.fileList.push(file
        }
        this.uploadList = JSON.parse(JSON.stringify(this.fileList))
        this.$emit('change-file-list', this.fileList);
      } catch (error) {
        // 清除 正在上传的文件中
        this.uploadList.splice(this.uploadList.indexOf(option.file), 1);
      }
    },
    handleProgress: function (event, file, fileList) {
      // console.log(file)
    },
    clearFiles () {
      this.uploadList = [];
      this.fileList = [];
      this.$refs._upload.clearFiles();
    },
    handleChange (file, fileList) {
     
    },
    /**上传文件前*/
    handleBeforeUpload (file) {
    var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase();
      let extension = true;
      if (this.fileType.length > 0 && this.fileType.indexOf(testmsg) === -1) {
        extension = false;
      }
      if (!extension) {
       
        this.uploadList.splice(this.uploadList.indexOf(file), 1);
        return false;
      }
      //判断文件大小
      if (this.size && file.size > this.size * 1024 * 1024) {
       
        this.uploadList.splice(this.uploadList.indexOf(file), 1);
        return false;
      }
      // 图片大小大于2M进行图片压缩
      if (file.size / 1024 / 1024 > 2) {
        console.log(file)
        const that = this
        return new Promise(resolve => {
          const reader = new FileReader()
          const image = new Image()
          image.onload = (imageEvent) => {
            const canvas = document.createElement('canvas') // 创建画布
            const context = canvas.getContext('2d')         // 画布为2d
            const width = image.width * that.quality        // 图片宽度 * 压缩比例
            const height = image.height * that.quality      // 图片高度 * 压缩比例
            canvas.width = width                            // 画布宽度
            canvas.height = height                          // 画布宽度
            context.clearRect(0, 0, width, height)
            context.drawImage(image, 0, 0, width, height)
            const dataUrl = canvas.toDataURL(file.type)     //图片转路径
            const blobData = that.dataURLtoBlob(dataUrl, file.type) //图片转二进制
            console.log(blobData)
            resolve(blobData)
          }
          reader.onload = e => { image.src = e.target.result }
          reader.readAsDataURL(file)
        })
      } else {
        return true
      }
    },
    //图片转二进制
    dataURLtoBlob (dataURL, type) {
      var binary = atob(dataURL.split(',')[1])
      var array = []
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i))
      }
      return new Blob([new Uint8Array(array)], { type: type })
    },
    /**失败*/
    handleError (err, file, fileList) {
      this.isZhaoZi = false;
      console.log(file);
      this.uploadList.splice(this.uploadList.indexOf(file), 1);
    },
    /**成功*/
    handleSuccess (res, file, fileList) {
    },
    handleExceed (files, fileList) {
      // 移除保存的正在上传的文件
      this.uploadList.splice(this.uploadList.indexOf(files), 1);
     
    },
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值