vue+elementUI+七牛上传前等比例压缩图片

准备工作:

  1. npm install compressorjs

    github地址

  2. npm install qiniu-js

    七牛sdk地址

  3. 从后台获取七牛上传的token

说明:

1.我们需求是图片宽度超过600像素的, 压缩到宽度600像素, 低于600像素的不做处理, 所以需要在上传前计算图片宽度.

2.具体的压缩参数请去github上看一下, 有帮助的话也star一下作者吧.

代码片段:

0.引包

import Compressor from 'compressorjs'
import * as qiniu from 'qiniu-js'

1.element upload组件

    qiniuToken:从后台拿七牛上传token

    我们需要自定义上传行为使用http-request, http-request会覆盖掉默认action

<el-upload
                action="http://upload-z2.qiniup.com"
                :data="{token:qiniuToken}"
                :http-request="customUpload"
                list-type="picture-card"
                :disabled="false"
                :before-upload="beforeUpload"
                :show-file-list="false"
              >

2.beforeUpload方法

beforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      // 获取图片宽度
      const _URL = window.URL || window.webkitURL
      const img = new Image()
      img.onload = function() {
        this.imgWidth = img.width
      }
      img.src = _URL.createObjectURL(file)

      return isJPG && isLt5M
    },

3.customUpload方法

customUpload(file) {
      const _this = this
      // 尺度大于600像素,进行压缩
      new Compressor(file.file, {
        quality: this.imgWidth > 600 ? 0.8 : 1,
        maxWidth: 500,
        success(compressFile) {
          // 七牛上传
          const config = {
            useCdnDomain: true, // 表示是否使用 cdn 加速域名,为布尔值,true 表示使用,默认为 false。
            region: null // 根据具体提示修改上传地区,当为 null 或 undefined 时,自动分析上传域名区域
          }
          const putExtra = {
            fname: '', // 文件原文件名
            params: {}, // 用来放置自定义变量
            mimeType: null // 用来限制上传文件类型,为 null 时表示不对文件类型限制;限制类型放到数组里: ["image/png", "image/jpeg", "image/gif"]
          }
          const observable = qiniu.upload(compressFile, null, file.data.token, putExtra, config)
          observable.subscribe({
            error: (err) => {
              // 失败报错信息
              console.log(err)
            },
            complete: (res) => {
              //这里会返回成功后的key, 逻辑需要自己处理
              _this.temp.listPic = _this.qiniuPre + res.key
            }
          })
        },
        error(err) {
          console.log(err.message)
        }
      })
    },

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值