阿里雲視頻點播功能,客戶端上傳,javascript SDK 使用

阿里雲文檔地址:https://help.aliyun.com/document_detail/52204.html?spm=a2c4g.11174283.6.1041.60ce149bIGfVYM;javascript

web端SDK上傳demo地址:https://help.aliyun.com/document_detail/51992.html?spm=a2c4g.11186623.4.2.44256bd1scfNId,能夠下載jquery和vue的使用示例;html

 

上傳地址和憑證方式(推薦使用)

第一步請求獲取的上傳地址和憑證初始化時無需設置,而是在開始上傳開始後觸發的onUploadStarted回調中調用setUploadAuthAndAddress(uploadFileInfo, uploadAuth, uploadAddress,videoId);方法進行設置。當token超時,會觸發onUploadTokenExpired回調,須要調用resumeUploadWithAuth(uploadAuth)方法,設置新的上傳憑證繼續上傳。vue

文檔示例代碼(javascript h5):java

  1. var uploader = new AliyunUpload.Vod({
  2. //阿里帳號ID,必須有值 ,值的來源https://help.aliyun.com/knowledge_detail/37196.html
  3. userId:"122"
  4. //分片大小默認1M,不能小於100K
  5. partSize: 1048576,
  6. //並行上傳分片個數,默認5
  7. parallel: 5,
  8. //網絡緣由失敗時,從新上傳次數,默認爲3
  9. retryCount: 3,
  10. //網絡緣由失敗時,從新上傳間隔時間,默認爲2秒
  11. retryDuration: 2,
  12. //是否上報上傳日誌到點播,默認爲true
  13. enableUploadProgress: true,
  14. // 開始上傳
  15. 'onUploadstarted': function (uploadInfo) {
  16. log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
  17. //上傳方式1, 須要根據uploadInfo.videoId是否有值,調用點播的不一樣接口獲取uploadauth和uploadAddress,若是videoId有值,調用刷新視頻上傳憑證接口,不然調用建立視頻上傳憑證接口
  18. if (uploadInfo.videoId) {
  19. // 若是 uploadInfo.videoId 存在, 調用 刷新視頻上傳憑證接口(https://help.aliyun.com/document_detail/55408.html)
  20. }
  21. else{
  22. // 若是 uploadInfo.videoId 不存在,調用 獲取視頻上傳地址和憑證接口(https://help.aliyun.com/document_detail/55407.html)
  23. }
  24. //從點播服務獲取的uploadAuth、uploadAddress和videoId,設置到SDK裏
  25. uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId);
  26. }
  27. // 文件上傳成功
  28. 'onUploadSucceed': function (uploadInfo) {
  29. log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);
  30. },
  31. // 文件上傳失敗
  32. 'onUploadFailed': function (uploadInfo, code, message) {
  33. log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
  34. },
  35. // 文件上傳進度,單位:字節
  36. 'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
  37. log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(loadedPercent * 100) + "%");
  38. },
  39. // 上傳憑證超時
  40. 'onUploadTokenExpired': function (uploadInfo) {
  41. console.log("onUploadTokenExpired");
  42. //實現時,根據uploadInfo.videoId調用刷新視頻上傳憑證接口從新獲取UploadAuth
  43. //https://help.aliyun.com/document_detail/55408.html
  44. //從點播服務刷新的uploadAuth,設置到SDK裏
  45. uploader.resumeUploadWithAuth(uploadAuth);
  46. },
  47. //所有文件上傳結束
  48. 'onUploadEnd':function(uploadInfo){
  49. console.log("onUploadEnd: uploaded all the files");
  50. }

vue使用該方式的話,須要注意的幾點:jquery

1.引用問題ios

      (3)  使用的vue2.0,能夠將下載的sdk正常引用;es6

      (2)  使用vue3.0的引用,在public文件夾下創建目錄名稱例如lib,將sdk放入該目錄下,在index.html頁面引用時,就是web

   <script src="/lib/js/es6-promise.min.js"></script>
  <script src="/lib/js/aliyun-oss-sdk-5.3.1.min.js"></script>
  <script src="/lib/js/aliyun-upload-sdk-1.5.0.min.js"></script>
2.vue文件中的使用,來自demo:
<script>
  import axios from 'axios'

  export default {
    data () {
      return {
        timeout: '',
        partSize: '',
        parallel: '',
        retryCount: '',
        retryDuration: '',
        region: 'cn-shanghai',
        userId: '1303984639806000',
        file: null,
        authProgress: 0,
        uploadDisabled: true,
        resumeDisabled: true,
        pauseDisabled: true,
        uploader: null,
        statusText: '',
      }
    },
    methods: {
      fileChange (e) {
        this.file = e.target.files[0]
        if (!this.file) {
          alert("請先選擇須要上傳的文件!")
          return
        }
        var Title = this.file.name
        var userData = '{"Vod":{}}'
        if (this.uploader) {
          this.uploader.stopUpload()
          this.authProgress = 0
          this.statusText = ""
        }
        this.uploader = this.createUploader()
        console.log(userData)
        this.uploader.addFile(this.file, null, null, null, userData)
        this.uploadDisabled = false
        this.pauseDisabled = true
        this.resumeDisabled = true
      },
      authUpload () {
        // 而後調用 startUpload 方法, 開始上傳
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.uploadDisabled = true
          this.pauseDisabled = false
        }
      },
      // 暫停上傳
      pauseUpload () {
        if (this.uploader !== null) {
          this.uploader.stopUpload()
          this.resumeDisabled = false
          this.pauseDisabled = true
        }
      },
      // 恢復上傳
      resumeUpload () {
        if (this.uploader !== null) {
          this.uploader.startUpload()
          this.resumeDisabled = true
          this.pauseDisabled = false
        }
      },
      createUploader (type) {
        let self = this
        let uploader = new AliyunUpload.Vod({
          timeout: self.timeout || 60000,
          partSize: self.partSize || 1048576,
          parallel: self.parallel || 5,
          retryCount: self.retryCount || 3,
          retryDuration: self.retryDuration || 2,
          region: self.region,
          userId: self.userId,
          // 添加文件成功
          addFileSuccess: function (uploadInfo) {
            self.uploadDisabled = false
            self.resumeDisabled = false
            self.statusText = '添加文件成功, 等待上傳...'
            console.log("addFileSuccess: " + uploadInfo.file.name)
          },
          // 開始上傳
          onUploadstarted: function (uploadInfo) {
            // 若是是 UploadAuth 上傳方式, 須要調用 uploader.setUploadAuthAndAddress 方法
            // 若是是 UploadAuth 上傳方式, 須要根據 uploadInfo.videoId是否有值,調用點播的不一樣接口獲取uploadauth和uploadAddress
            // 若是 uploadInfo.videoId 有值,調用刷新視頻上傳憑證接口,不然調用建立視頻上傳憑證接口
            // 注意: 這裏是測試 demo 因此直接調用了獲取 UploadAuth 的測試接口, 用戶在使用時須要判斷 uploadInfo.videoId 存在與否從而調用 openApi
            // 若是 uploadInfo.videoId 存在, 調用 刷新視頻上傳憑證接口(https://help.aliyun.com/document_detail/55408.html)
            // 若是 uploadInfo.videoId 不存在,調用 獲取視頻上傳地址和憑證接口(https://help.aliyun.com/document_detail/55407.html)
            if (!uploadInfo.videoId) {
              let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
              axios.get(createUrl).then(({data}) => {
                let uploadAuth = data.UploadAuth
                let uploadAddress = data.UploadAddress
                let videoId = data.VideoId
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)                
              })
              self.statusText = '文件開始上傳...'
              console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
            } else {
              // 若是videoId有值,根據videoId刷新上傳憑證
              // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
              let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
              axios.get(refreshUrl).then(({data}) => {
                let uploadAuth = data.UploadAuth
                let uploadAddress = data.UploadAddress
                let videoId = data.VideoId
                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
              })
            }
          },
          // 文件上傳成功
          onUploadSucceed: function (uploadInfo) {
            console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
            self.statusText = '文件上傳成功!'
          },
          // 文件上傳失敗
          onUploadFailed: function (uploadInfo, code, message) {
            console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
            self.statusText = '文件上傳失敗!'
          },
          // 取消文件上傳
          onUploadCanceled: function (uploadInfo, code, message) {
            console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
            self.statusText = '文件已暫停上傳'
          },
          // 文件上傳進度,單位:字節, 能夠在這個函數中拿到上傳進度並顯示在頁面上
          onUploadProgress: function (uploadInfo, totalSize, progress) {
            console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
            let progressPercent = Math.ceil(progress * 100)
            self.authProgress = progressPercent
            self.statusText = '文件上傳中...'
          },
          // 上傳憑證超時
          onUploadTokenExpired: function (uploadInfo) {
            // 上傳大文件超時, 若是是上傳方式一即根據 UploadAuth 上傳時
            // 須要根據 uploadInfo.videoId 調用刷新視頻上傳憑證接口(https://help.aliyun.com/document_detail/55408.html)從新獲取 UploadAuth
            // 而後調用 resumeUploadWithAuth 方法, 這裏是測試接口, 因此我直接獲取了 UploadAuth
            let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
            axios.get(refreshUrl).then(({data}) => {
              let uploadAuth = data.UploadAuth
              uploader.resumeUploadWithAuth(uploadAuth)
              console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
            })
            self.statusText = '文件超時...'
          },
          // 所有文件上傳結束
          onUploadEnd: function (uploadInfo) {
            console.log("onUploadEnd: uploaded all the files")
            self.statusText = '文件上傳完畢'
          }
        })
        return uploader
      }
    }
  }
</script>

;axios

相關文章
相關標籤/搜索