canvas处理图片清晰度后使用七牛云上传

引入七牛插件
import * as qiniu from 'qiniu-js'
 
 
 
// 处理图片
  private transformCanvas(file: any, cb: any) {
    const img = new Image()
    img.onload = function () {
      const canvas = document.createElement('canvas')
      const [w, h] = [img.width, img.height]
      canvas.width = w
      canvas.height = h
      const ctx: any = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, w, h)
      canvas.toBlob(
        function (blobObj) {
          cb(blobObj)
        },       
   'image/jpeg',
        0.8  //当请求图片格式为image/jpeg或者image/webp时用来指定图片展示质量。如果这个参数的值不在指定类型与范围之内,则使用默认值,其余参数将被忽略。
      )
    }
    img.src = window.URL.createObjectURL(file)
  }
 
 
 
private uploadImg(uploader: any) {
    //获取76云key,token
    this.transformCanvas(uploader.file, (file: any) => {
      this.$service('upload-token', 'get').then(
        (res: any) => {
          const { key, token, qiniuDomain } = res.data
          //创建76云上传
          let observable = this.$qiniu.upload(file, key, token, {}, {})
          const that = this
          const subscription = observable.subscribe({
            next(res: any) {},
            error: (err: any) => {
              this.$message.error(err.message)
              subscription.unsubscribe()
            },
            complete(res: any) {
              that.downloadUrl(res.key, uploader.file)
            }
          })
        }
      )
    })
  }
 
// 下载图片
  private downloadUrl(key: any, file: any) {
    let params = {
      key: key
    }
    this.imgLoading = true
    this.$service(url', 'get', params).then(
      (res: any) => {
        this.fileLists.push({
          name: file.name,
          uid: file.uid,
          key: key,
          url: res.data
        })
        this.imgLoading = false
      }
    )
  }
 
 
posted @ 2020-07-31 10:35  lucy123  阅读(253)  评论(0编辑  收藏  举报