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
      }
    }
  }
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Vue3是一种行的JavaScript框架,用于构建用户界面。它具有响应式数据绑定、组件化开发和虚拟DOM等特性,使得开发者可以更高效地构建交互式的Web应用程序。 要在Vue3中实现上传图片到阿里云OSS,你可以按照以下步骤进行操作: 1. 安装依赖:首先,你需要安装阿里云OSSJavaScript SDK。可以使用npm或yarn命令来安装,例如: ``` npm install ali-oss ``` 2. 配置OSS客户端:在Vue3的代码中,你需要创建一个OSS客户端实例,并配置相关参数,如AccessKeyId、AccessKeySecret、Endpoint等。这些参数可以在阿里云OSS控制台中获取。 3. 创建上传组件:在Vue3中,你可以创建一个上传组件,用于选择图片文件并触发上传操作。可以使用`<input type="file">`元素来实现文件选择功能,并监听其`change`事件。 4. 上传图片:在上传组件中,你可以编写上传图片的逻辑。当用户选择了图片文件后,你可以通过OSS客户端调用`put`方法来上传图片文件阿里云OSS。 下面是一个简单的示例代码,演示了如何在Vue3中上传图片到阿里云OSS: ```javascript <template> <div> <input type="file" @change="handleFileChange"> </div> </template> <script> import OSS from 'ali-oss'; export default { methods: { handleFileChange(event) { const file = event.target.files[0]; const client = new OSS({ accessKeyId: 'your-access-key-id', accessKeySecret: 'your-access-key-secret', bucket: 'your-bucket-name', region: 'your-oss-region', // 其他配置参数... }); // 生成唯一的文件名 const fileName = Date.now() + '-' + file.name; // 调用OSS客户端的put方法上传文件 client.put(fileName, file).then(response => { console.log('上传成功', response); // 在这里可以处理上传成功后的逻辑 }).catch(error => { console.error('上传失败', error); // 在这里可以处理上传失败后的逻辑 }); } } } </script> ``` 请注意,上述代码中的`your-access-key-id`、`your-access-key-secret`、`your-bucket-name`和`your-oss-region`需要替换为你自己的阿里云OSS相关信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值