前端实现阿里云oss上传 进度条

阿里云oss内部配置这里不再赘述 需要请搜索百度

桶内跨域配置

重要 :注意要暴露headers
在这里插入图片描述

实例化

const OSS = require('ali-oss')
const client = new OSS({
  region: 'oss-cn-beijing', // oss存储地域   创建桶的时候选择的地域
  accessKeyId: '入口id', // 入口id   id和秘钥前往accesskey 进行配置
  accessKeySecret: '秘钥', // 秘钥
  bucket: 'hrdemo', // 存储通  创建的桶名
  secure: true   
})

上传代码

此处较为重要
在没有设置parSize的时候上传文件 发现progress 打印的值percentage 等了很长时间依旧是显示了个0 和 1
检查后发现 每传输完一个分片 进度条会走一个百分比 不设置的话由于partsize过大 可能导致很长时间进度条都看不到效果

参数配置参考https://help.aliyun.com/document_detail/111268.html

 // img 文件夹下  obj.file.name 文件的名字 obj.file文件对象
      client.multipartUpload('img/' + obj.file.name, obj.file,
        {
          // 进度条的配置项
          progress: function(percentage) { // 获取进度条的值
            console.log(percentage)
            // console.log(p * 100)
            this.percent = percentage * 100
          },
          // 每传输完一个分片 进度条会走一个百分比 不设置的话由于partsize过大 可能导致很长时间进度条都看不到效果
          partSize: 102400 // 指定上传的每个分片的大小,范围为100 KB~5 GB。单个分片默认大小为1 * 1024 * 1024(即1 MB)
        }
      ).then(response => {
        console.log(response)
        if (response.res.status === 200) {
          console.log('上传了')
          this.imageUrl = response.url // 把上传后的地址给img
          this.showProgress = false
        }
      }).catch(function(err) {
        console.error('error: ', err)
      })

put方式

该方式没有回调 如果有进度条的需求 选择multipartUpload方法上传文件

   client.put('img/' + obj.file.name, obj.file).then(response => {
        console.log(response)
        if (response.res.status === 200) {
          console.log('上传了')
          this.imageUrl = response.url // 把上传后的地址给img
          this.showProgress = false
        }
      }).catch(function(err) {
        console.error('error: ', err)
      })

上传后的效果图

图片位于桶根目录下的img文件中
在这里插入图片描述
可参考的博客地址: https://www.jianshu.com/p/1ea2e5964b10

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐