ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

el-upload 上传压缩图片

2022-05-07 15:34:01  阅读:151  来源: 互联网

标签:el canvas const naturalHeight upload naturalWidth var 上传


随着手机像素越来越高,拍出来的照片大小很大,一般都是几兆(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

 

标签:el,canvas,const,naturalHeight,upload,naturalWidth,var,上传
来源: https://www.cnblogs.com/feipengting/p/16242709.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有