VUE-利用OSS BrowserJS-SDK实现阿里OSS前端上传

项目中遇到利用阿里OSS上传文件,线上很多示例用到了各种SDK,却没有看到OSS BrowserJS-SDK相关示例,鉴于脑子不好使,记一下。

  1. 封装upload相关组件

  2. 使用npm安装SDK的开发包

    npm install ali-oss
    
  3. 在组件中实例化SDK并使用

    上述四个参数可通过调用后台接口获取,若前端直接封装,容易暴露。

  4. 前往(控制台-对象存储OSS-基本设置)配置CORS

    (详见官方文档)

  5. methods中封装相关上传方法

    export default {
    name:'aliUpload',
    data () {
    return {
      videoName:'',
      videoUrl: '',
      size:''
    }
    },
    methods:{
    doUpload(event){
      this.$emit('getProgress',0)
      let file = event.target.files
      this.size = file[0].size
      let tmpArr = file[0].name.split('.')
      let tmpName = md5(Date.now() + tmpArr[0])
      tmpName = tmpName + '.' + tmpArr[1]
      this.multipartUpload(tmpName,file[0])
    },    
    multipartUpload(upName,upFile){
      //Vue中封装的分片上传方法(详见官方文档)
      let _this = this
      const progress = async function (p) {
        //项目中需获取进度条,故调用进度回调函数(详见官方文档)
        _this.$emit('getProgress',Math.round(p*100))
      }
      try {
        let result = client.multipartUpload(upName,upFile, {
        progress,
        meta: {
          year: 2017,
          people: 'test'
        }
        }).then(res=>{
          _this.videoUrl = res.res.requestUrls[0].split('?')[0]
          let info = {}
          info.name = res.name
          info.size = _this.size
          info.videoUrl = _this.videoUrl
          _this.$emit('getUrl',info)
          let head = client.head(upName);
    
        }).catch(err=>{
          console.log(err)
        });
    
      } catch (e) {
    // 捕获超时异常
        if (e.code === 'ConnectionTimeoutError') {
          console.log("Woops,超时啦!");
        }
        console.log(e)
      }
    },
    
    }
    }
    
  6. 外部引入组件使用

猜你喜欢

转载自www.cnblogs.com/yw-elm/p/VUEli-yongOSS-BrowserJSSDK-shi-xian-a-liOSS-qian-d.html