el-upload 上传压缩图片

随着手机像素越来越高,拍出来的照片大小很大,一般都是几兆(MB)。但是上传的文件质量越高,上传和预览的时候就增加网络负担。为了解决上传到服务器上照片大的问题,考虑到上传就压缩一下图片,然后在上传到服务器。这里我们用的的上传组件是elmentui的el-upload,废话不多说,直接上代码:

      <el-upload class="avatar-uploader" ref="upfile" :action="FileUpSever" :show-file-list="false" :headers="token"
        :data="ruleForm" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-change="handleChange"
        multiple accept="image/gif,image/jpeg,image/png,text/plain,application/pdf,application/xls" :limit="10"
        :on-exceed="handleExceed" :file-list="filedata">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>

这里主要用到上传前,判断是图片文件就压缩

      beforeAvatarUpload(file) {
        var _this = this
        const fileName = file.name
        const m = fileName.match(/\.(\w+)(#|\?|$)/)
        const fileType = (m && m[1]).toString().toLowerCase()
        const allowHook = ['mp4', 'ogv', 'ogg', 'webm', 'wav', 'mp3', 'ogg', 'acc', 'webm', 'amr', 'doc', 'docx',
          'xlsx',
          'xls', 'pdf', 'jpg', 'jpeg', 'png', 'gif'
        ]
        const validType = (allowHook).includes(fileType)
        if (!validType) {
          const supprtTypes = '视频、文档、Excel、图片'
          this.$message.error('只支持' + supprtTypes + '类型文件上传')
          return false
        }
        if (fileName.indexOf('%') > -1 || fileName.indexOf('&') > -1) {
          this.$message.error('上传文件名称不能带有字符"%","&"')
          return false
        }
        const isLt10M = file.size / 1024 / 1024 < global.FileSize
        if (!isLt10M) {
          this.$message.error('上传资料大小不能超过 10MB!')
          return false
        }
        if (['jpg', 'jpeg', 'png'].includes(fileType)) {
          return new Promise((resolve, reject) => {
            tool.compress(file,
              (newfileex) => {
                console.log('newFile', newfileex)
                resolve(newfileex)
              })
          })
        }
      }

压缩用的到tool,重新写了一个工具类,然后引入调用

import tool from '@/utils/tool.js'

const tools = {
  compress(inputFile, callback) {
    const self = this;
    const reader = new FileReader();
    reader.readAsDataURL(inputFile);
    reader.onload = function(e) {
      //防止照片文件过大无法上传, 通过以下代码重新创建一个固定宽高的图片再上传
      var image = new Image();
      image.src = this.result; //转化为base64字符串
      self.base64img = image.src
      image.onload = function() {
        debugger
        var expectWidth = this.naturalWidth;
        var expectHeight = this.naturalHeight;
        if (this.naturalWidth > this.naturalHeight && this.naturalWidth > 800) {
          expectWidth = 800;
          expectHeight = (expectWidth * this.naturalHeight) / this.naturalWidth;
        } else if (this.naturalHeight > this.naturalWidth && this.naturalHeight > 1200) {
          expectHeight = 1200;
          expectWidth = (expectHeight * this.naturalWidth) / this.naturalHeight;
        }
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = expectWidth;
        canvas.height = expectHeight;
        ctx.drawImage(this, 0, 0, expectWidth, expectHeight);
        var dataurl = canvas.toDataURL('image/jpeg', 1);
        // 0到1之间的取值,主要用来选定图片的质量,默认值是0.92,超出    
        //范围也会选择默认值。
        // callback(dataurl)
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        //修改上传文件名,重新整理进fileList
        var newf = new File([u8arr], inputFile.name, {
          type: mime
        });
        newf.uid = inputFile.uid
        callback(newf)
      };
    };
  }
}

export default tools

 

posted @ 2022-05-07 15:22  蓬鹏  阅读(1384)  评论(0编辑  收藏  举报