图片压缩上传

2019-04-15  本文已影响0人  不醒的梦最美

vue项目使用el-upload 组件,实现图片压缩上传至服务器
感谢博客文章,文章中主要代码来自该博客:https://blog.csdn.net/liona_koukou/article/details/84860899

<el-upload :http-request="httpRequest"  list-type="picture-card" :drag="true" ref="upload" :accept="accept[item.MimeTypes]" :headers="headers" :show-file-list="false" :action="upImgUrl" :data="Object.assign({item:item,index:index,i:i},fileData)" :before-upload="beforeAvatarUpload" :on-error="unloadError" :on-success="unloadSucceed" :on-change="uploadChange" >              
</el-upload>

主要是

// 将blob 文件转为 file文件
new window.File([blob],file.name,{type:file.type})
compress(fileObj, callback) {
      let quality = 0.7 // 默认图片质量为0.7
      const _this = this;
      try {
        const image = new Image()
        image.src = URL.createObjectURL(fileObj);
        image.onload = function() {
          const that = this
          // 默认按比例压缩
          let w = that.width
          let h = that.height
          const scale = w / h
          w = fileObj.width || w
          h = fileObj.height || (w / scale)
          
          // 生成canvas
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 创建属性节点
          const anw = document.createAttribute('width')
          anw.nodeValue = w
          const anh = document.createAttribute('height')
          anh.nodeValue = h
          canvas.setAttributeNode(anw)
          canvas.setAttributeNode(anh)
          ctx.drawImage(that, 0, 0, w, h)
          // 图像质量
          if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
            quality = fileObj.quality
          }
          // quality值越小,所绘制出的图像越模糊
          const data = canvas.toDataURL('image/jpeg', quality)
          // 压缩完成执行回调
          const newFile = _this.convertBase64UrlToBlob(data)
          callback(newFile)
        }
      } catch (e) {
        console.log('压缩失败!')
      }
    },
    // 压缩图片转为blob 格式
    convertBase64UrlToBlob(urlData) {
      const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头,并转换为byte
      // 处理异常,将ascii码小于0的转换为大于0
      const ab = new ArrayBuffer(bytes.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      return new Blob([ab], { type: 'image/png' })
    },
    httpRequest(file){
      this.compress(file.file, function(blob) {
          // Blob 格式文件转为 file 格式
          var newFile=new window.File([blob],file.file.name,{type: file.file.type});
          // form 表单提交图片文件
          var formData = new FormData();
          formData.append("file",newFile);
          axios.post(file.action,formData,{headers:file.headers,timeout:30*60*1000}).then(data=>{
            file.onSuccess(data);
          })
        })
    }
上一篇下一篇

猜你喜欢

热点阅读