vue前端上传文件到阿里云oss的两种体式格局,put文件流上传,multipartUpload直接上传

引入阿里云oss的js

<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
<input type="file" name="file" @change='selectFile' multiple="multiple"/>上传图片/文件
mounted () {
  this.initConfig() // 挪用背景接口猎取阿里云上传下载通行证
}
methods: {
  initConfig () {
    // 初始化oss权限
    let url = 'document.getAccess'
    let params = {
       type: 'H'
    }
    this.$api.send(url, params).then((response) => {
      if (response.status === 200) {
        let data = response.body.data.data
        /* global OSS */ // 去掉esllint对OSS的校验
        this.client = new OSS.Wrapper({
          region: 'oss-cn-shenzhen',
          accessKeyId: 'your accessKeyId',
          accessKeySecret: 'your accessKeySecret',
          stsToken: 'your stsToken',
          bucket: 'xx'
       })
     }
   })
  },
  selectFile (e) {
    // 挑选文件
    for (let i = 0; i < e.target.files.length; i++) {
      this.pushFile(e.target.files[i])
    }
  },
  pushFile (file) {
    let that = this
    let _file = file
    var storeAs = '' // 传到oss上的名字
    // 挪用上传要领
    that.client.multipartUpload('cloudStorage/' + storeAs, _file, {
      progress: function* (percentage) {
        let fileloadingNum = Math.ceil(percentage * 100) + '%'
        console.log(fileloadingNum) // 上传文件进度
      }
    }).then(function (result) {
      // 挪用背景增加文件的接口
      let url = 'netdisc.addDoc'
      let params = {
        data: 'xx'
      }
      that.$api.send(url, params).then((response) => {
        if (response.status === 200) {
          // 上传胜利
        }
      })
    }).catch(function (err) {
      // 上传失利,弹出上传失利的音讯
    })
  }
}

假如传到阿里云的图片要展现出来,要在src的图片途径背面加上阿里云后缀,如许用苹果手机拍的照片就不会涌现图片翻转的题目,像如许
xxx.JPG?x-oss-process=image/auto-orient,1/resize,m_fill,w_1600

假如图片要用canvas做紧缩, 取得的是base64数据,要转换成blob对象,再转为buffer流。用put上传
有些手机不支撑canvas直接转为blob对象能够引入canvas-to-blob.min.js 将canvas转为blob对象
blob插件地点: https://github.com/blueimp/Ja…
取得图片的方向,引入exif.js
exif.js 官网地点 http://code.ciaoca.com/javasc…
项目中都是用<script>标签直接在index.html中援用的

  pushFile (file) {
    let that = this
    if (['jpeg', 'png', 'jpg'].indexOf(file.type.split('/')[1]) < 0) {
      alert('只支撑jpg/png花样的图片')
      return false
    }
    // orient=>照片的角度
    /* global EXIF */
    let orient
    EXIF.getData(file, function () {
      orient = EXIF.getTag(this, 'Orientation')
    })
    // 紧缩图片须要的一些元素和对象
    let reader = new FileReader()
    let img = new Image()
    // 挑选得是图片
    if (file.type.indexOf('image') === 0) {
      reader.readAsDataURL(file)
    }
    // 缩放图片须要的canvas
    let canvas = document.createElement('canvas')
    let context = canvas.getContext('2d')
    // base64 地点加载完后
    img.onload = function () {
      // 图片原始尺寸
      let originWidth = this.width
      let oringinHeight = this.height
      // 最大尺寸限定
      let maxWidth = 800
      let maxHeight = 800
      // 目的尺寸
      let targetWidth = originWidth
      let targetHeight = oringinHeight
      // 图片尺寸凌驾800x800的限定
      if (originWidth > maxWidth || oringinHeight > maxHeight) {
        if (originWidth / oringinHeight > maxWidth / maxHeight) {
          // 更宽
          targetWidth = maxWidth
          targetHeight = Math.round(maxWidth * (oringinHeight / originWidth))
        } else {
          targetHeight = maxHeight
          targetWidth = Math.round(maxHeight * (originWidth / oringinHeight))
        }
      }
      // canvas 对图片举行缩放
      canvas.width = targetWidth
      canvas.height = targetHeight
      // 消灭画布
      context.clearRect(0, 0, targetWidth, targetHeight)
      // 图片紧缩
      context.drawImage(img, 0, 0, targetWidth, targetHeight)
      if (orient !== '' && orient !== 1) {
        // orient === 1是一般的
          switch (orient) {
            case 6: // 须要顺时针向左90度扭转
              that.rotateImg(img, 'left', canvas, targetWidth, targetHeight)
              break
            case 8: // 须要逆时针向右90度扭转
              that.rotateImg(img, 'right', canvas, targetWidth, targetHeight)
              break
            case 3: // 须要180度扭转
              that.rotateImg(img, 'right', canvas, targetWidth, targetHeight)
              that.rotateImg(img, 'right', canvas, targetWidth, targetHeight)
              break
          }
        }
        if (canvas.toBlob) {
          canvas.toBlob(function (blob) {
            // 在这里完成上传操纵
            let reader2 = new FileReader()
            reader2.readAsArrayBuffer(blob)
            reader2.onload = function (event) {
              let buffer = new OSS.Buffer(event.target.result)
              that.client.put(storeAs, buffer).then((result) => {
                if (result.url) {
                  // 取得图片地点
                  that.src= result.url
                }
              }).catch((err) => {
                console.log(err)
                alert('上传失利, 请从新上传')
              })
            }
          }, file.type || 'image/png')
        }
      }
    rotateImg (img, direction, canvas, targetWidth, targetHeight) {
      // 最小与最大扭转方向,图片扭转4次后回到原方向
      var minstep = 0
      var maxstep = 3
      if (img === null) return
      // img的高度和宽度不能在img元素隐蔽后猎取,不然会失足
      var step = 2
      if (step === null) {
        step = minstep
      }
      if (direction === 'right') {
        step++
        // 扭转到原位置,即凌驾最大值
        step > maxstep && (step = minstep)
      } else {
        step--
        step < minstep && (step = maxstep)
      }
      // 扭转角度以弧度值为参数
      let degree = step * 90 * Math.PI / 180
      var ctx = canvas.getContext('2d')
      switch (step) {
        case 0:
          canvas.width = targetWidth
          canvas.height = targetHeight
          ctx.clearRect(0, 0, targetWidth, targetHeight)
          ctx.drawImage(img, 0, 0, targetWidth, targetHeight)
          break
        case 1:
          canvas.width = targetHeight
          canvas.height = targetWidth
          ctx.rotate(degree)
          ctx.clearRect(0, 0, targetHeight, targetWidth)
          ctx.drawImage(img, 0, -targetHeight, targetWidth, targetHeight)
          break
        case 2:
          canvas.width = targetWidth
          canvas.height = targetHeight
          ctx.rotate(degree)
          ctx.clearRect(0, 0, targetWidth, targetHeight)
          ctx.drawImage(img, -targetWidth, -targetHeight, targetWidth, targetHeight)
          break
        case 3:
          canvas.width = targetHeight
          canvas.height = targetWidth
          ctx.rotate(degree)
          ctx.clearRect(0, 0, targetHeight, targetWidth)
          ctx.drawImage(img, -targetHeight, 0, targetWidth, targetHeight)
          break
      }
    }
  }
    原文作者:流年朝朝
    原文地址: https://segmentfault.com/a/1190000015545333
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞