zoukankan      html  css  js  c++  java
  • 阿里云VOD 视频点播(二)、VUE视频上传,视频播放

    一,VUE视频上传

    (1),视频上传引入的js文件,在index.html文件里面引入js,如下图
    在这里插入图片描述
    js文件在官网可以下载然后放在自己的项目里面,下载下面的js文件引入项目
    JavaScript上传SDK 1.5.0
    示例代码(jquery和Vue)

    <script src="./aliyun-upload-sdk/lib/es6-promise.min.js"></script>
      <script src="./aliyun-upload-sdk/lib/aliyun-oss-sdk-5.3.1.min.js"></script>
      <script src="./aliyun-upload-sdk/aliyun-upload-sdk-1.5.0.min.js"></script>
    

    (2),封装上传组件
    在这里插入图片描述

    <template>
      <div class="container">
        <!--<div class="setting">
          <div class="input-control">
            <label for="partSize">分片大小(构造参数 partSize, 默认 1048576):</label>
            <input type="text" class="form-control" id="partSize" v-model="partSize" placeholder="输入分片大小, 单位bit, 最小100k">
          </div>
          <div class="input-control">
            <label for="parallel">上传分片数(构造参数 parallel, 默认 5):</label>
            <input type="text" class="form-control" id="parallel" v-model="parallel" placeholder="输入并行上传分片个数, 默认为5">
          </div>
          <div class="input-control">
            <label for="retryCount">网络失败重试次数(构造参数 retryCount, 默认 3):</label>
            <input type="text" class="form-control" id="retryCount" v-model="retryCount" placeholder="输入网络失败重试次数, 默认为3">
          </div>
          <div class="input-control">
            <label for="retryDuration">网络失败重试间隔(构造参数 retryDuration, 默认 2):</label>
            <input type="text" class="form-control" id="retryDuration" v-model="retryDuration" placeholder="输入网络失败重试间隔, 默认2秒">
          </div>
          <div class="input-control">
            <label>配置项 region, 默认 cn-shanghai:</label>
            <select v-model="region">
              <option>cn-shanghai</option>
              <option>eu-central-1</option>
              <option>ap-southeast-1</option>
            </select>
          </div>
          <div class="input-control">
            <label>阿里云账号ID</label>
            <input type="text" class="form-control" v-model="userId" placeholder="输入阿里云账号ID">
            集成产品后需要使用用户自己的账号ID,<a href="https://help.aliyun.com/knowledge_detail/37196.html" target="_blank">如何获取帐号ID</a>
          </div>
        </div>-->
    
        <div class="upload">
          <div>
            <div class="filebox">
              <input type="file" id="fileUpload" @change="fileChange($event)" class="filebtn">
              <div class="flletit">选择视频</div>
            </div>
            <div class="filetitle">{{fileTitle}}</div>
            <label class="status">上传状态: <span>{{statusText}}</span></label>
          </div>
          <div class="upload-type">
            <el-button slot="trigger" size="small" type="primary"  @click="authUpload" :disabled="uploadDisabled">开始上传</el-button>
            <el-button style="margin-left: 10px;" size="small" type="danger" @click="pauseUpload" :disabled="pauseDisabled">暂停</el-button>
            <el-button slot="trigger" size="small" type="success"  :disabled="resumeDisabled" @click="resumeUpload">恢复上传</el-button>
          </div>
          <el-progress :text-inside="true" :stroke-width="15" :percentage=authProgress :status='authProgress == 100 ? "success":"text"'></el-progress>
        </div>
      </div>
    </template>
    <script>
    export default {
      data () {
        return {
          vid: '',
          fileTitle: '',
          timeout: '',
          partSize: '',
          parallel: '',
          retryCount: '',
          retryDuration: '',
          region: 'cn-shanghai',
          userId: '输入阿里云账号ID',
          file: null,
          authProgress: 0,
          uploadDisabled: true,
          resumeDisabled: true,
          pauseDisabled: true,
          uploader: null,
          statusText: ''
        }
      },
      methods: {
        emitEventVod () {
          this.authProgress = 0
          this.fileTitle = ''
          this.statusText = ''
          this.pauseDisabled = true
          this.resumeDisabled = true
          this.uploadDisabled = true
        },
        fileChange (e) {
          this.file = e.target.files[0]
          if (!this.file) {
            this.$message.error('请先选择需要上传的文件!')
            return
          }
          if (this.file.type !== 'video/mp4') {
            this.$message.error('请选择.mp4文件!')
            return
          }
          this.fileTitle = 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
          // eslint-disable-next-line
          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 title = uploadInfo.file.name.substr(0, uploadInfo.file.name.lastIndexOf('.'))
                self.$http.get('/oss/file/createUploadVideo', { params: { title: title, fileName: uploadInfo.file.name } }).then(({ data: res }) => {
                  if (res.code !== 0) {
                    return self.$message.error(res.msg)
                  }
                  let uploadAuth = res.data.UploadAuth
                  let uploadAddress = res.data.UploadAddress
                  let videoId = res.data.VideoId
                  self.vid = res.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刷新上传凭证
                self.$http.get('/oss/file/refreshUploadVideo', { params: { videoId: uploadInfo.videoId } }).then(({ data: res }) => {
                  if (res.code !== 0) {
                    return self.$message.error(res.msg)
                  }
                  let uploadAuth = res.data.UploadAuth
                  let uploadAddress = res.data.UploadAddress
                  let videoId = res.data.VideoId
                  self.vid = res.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
              self.$http.get('/oss/file/refreshUploadVideo', { params: { videoId: uploadInfo.videoId } }).then(({ data: res }) => {
                if (res.code !== 0) {
                  return self.$message.error(res.msg)
                }
                let uploadAuth = res.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 = '文件上传完毕'
              self.emitEvent(self.vid)
            }
          })
          return uploader
        },
        emitEvent (vid) {
          this.$emit('my-event', vid)
        }
      }
    }
    </script>
    <style>
      .container{
        text-align: center;
        line-height: 1;
      }
      .upload-type{
        margin: 15px 0;
      }
      .filebox{
         80px;
        height: 32px;
        color: #fff;
        background-color: #17B3A3;
        border-color: #17B3A3;
        position: relative;
        border-radius: 3px;
        text-align: center;
        line-height: 32px;
        margin: 0 auto;
      }
      .filebox .filebtn{
     100%;
        height: 100%;
        border: none;
        background: none;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    
      }
     .filebox .flletit{
        100%;
       height: 100%;
     }
      .filetitle{
        margin: 10px 0;
      }
      .status span{
        color: #FF4C52;
      }
    </style>
    
    

    (3),使用组件,渲染页面

    <template>
      <el-dialog :visible.sync="visible" :title="$t('oss.upload')" :close-on-click-modal="false" :close-on-press-escape="false">
        <uploadVod @my-event="getMyEvent" ref="childVod"></uploadVod>
      </el-dialog>
    </template>
    <script>
    
    import UploadVod from '../../../components/uploadvod'
    export default {
      components: {
        UploadVod
      },
      data () {
        return {
          visible: false
        }
      },
      methods: {
        init () {
          this.visible = true
          this.$refs.childVod.emitEventVod()
        },
        getMyEvent (vid) {
          console.log('接收的数据--------->' + vid)
          this.$message({
            message: '接收的数据---->' + vid,
            type: 'success'
          })
        }
      }
    }
    </script>
    
    

    二,VUE视频点播

    (1),封装的组件,引入网络js文件

    <template>
        <el-dialog :visible.sync="visible" title="视频播放" :close-on-click-modal="false" :close-on-press-escape="false"
                   :before-close="closeVal">
            <div :id="playerId" class="prism-player"/>
        </el-dialog>
    </template>
    
    <script>
    export default {
      props: {
        aliplayerSdkPath: {
          // Aliplayer 代码的路径
          type: String,
          default: '//g.alicdn.com/de/prismplayer/2.8.2/aliplayer-min.js'
        }
      },
      data () {
        return {
          visible: false,
          playerId: 'aliplayer_' + Math.random().toString(36).substr(2),
          scriptTagStatus: 0,
          isReload: false,
          instance: null,
          vid: '',
          playauth: '',
          cover: ''
        }
      },
      mounted () {
        if (window.Aliplayer !== undefined) {
          // 如果全局对象存在,说明编辑器代码已经初始化完成,直接加载编辑器
          this.scriptTagStatus = 2
          this.initAliplayer()
        } else {
          // 如果全局对象不存在,说明编辑器代码还没有加载完成,需要加载编辑器代码
          this.insertScriptTag()
        }
      },
      methods: {
        async init (vid) {
          this.visible = true
          await this.$http.get('/oss/file/getVideoPlayAuth', { params: { videoId: vid } }).then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            console.log('fetch---', res)
            this.cover = res.data.CoverUrl
            this.playauth = res.data.PlayAuth
            this.vid = res.data.VideoId
          })
          // eslint-disable-next-line
                    if (window.Aliplayer !== undefined) {
            // 如果全局对象存在,说明编辑器代码已经初始化完成,直接加载编辑器
            this.scriptTagStatus = 2
            this.initAliplayer()
          } else {
            // 如果全局对象不存在,说明编辑器代码还没有加载完成,需要加载编辑器代码
            this.insertScriptTag()
          }
        },
        closeVal () {
          console.log('-----2-----------')
          this.$emit('my-event', 0)
        },
        insertScriptTag () {
          const _this = this
          let playerScriptTag = document.getElementById('playerScriptTag')
          // 如果这个tag不存在,则生成相关代码tag以加载代码
          if (playerScriptTag === null) {
            playerScriptTag = document.createElement('script')
            playerScriptTag.type = 'text/javascript'
            playerScriptTag.src = _this.aliplayerSdkPath
            playerScriptTag.id = 'playerScriptTag'
            const s = document.getElementsByTagName('head')[0]
            s.appendChild(playerScriptTag)
          }
          if (playerScriptTag.loaded) {
            _this.scriptTagStatus++
          } else {
            playerScriptTag.addEventListener('load', () => {
              _this.scriptTagStatus++
              playerScriptTag.loaded = true
              _this.initAliplayer()
            })
          }
          _this.initAliplayer()
        },
        initAliplayer () {
          const _this = this
          // scriptTagStatus 为 2 的时候,说明两个必需引入的 js 文件都已经被引入,且加载完成
          if (
            _this.scriptTagStatus === 2 &&
                        (_this.instance === null || _this.reloadPlayer)
          ) {
            _this.instance && _this.instance.dispose()
    
            document.querySelector('#' + _this.playerId).innerHTML = ''
    
            // Vue 异步执行 DOM 更新,这样一来代码执行到这里的时候可能 template 里面的 script 标签还没真正创建
            // 所以,我们只能在 nextTick 里面初始化 Aliplayer
            _this.$nextTick(() => {
              // eslint-disable-next-line
                            const player = new Aliplayer({
                'id': _this.playerId,
                'width': '100%',
                'height': '500px',
                'autoplay': true,
                'isLive': false,
                'rePlay': false,
                'playsinline': true,
                'preload': true,
                'controlBarVisibility': 'hover',
                'useH5Prism': true,
                'vid': _this.vid,
                'playauth': _this.playauth,
                'cover': _this.cover
              }, function (player) {
                // console.log('123')
              })
            })
          }
        }
      }
    }
    </script>
    <style>
        @import url(//g.alicdn.com/de/prismplayer/2.8.2/skins/default/aliplayer-min.css);
    </style>
    
    

    (2),使用组件渲染页面

    <template>
      <el-card shadow="never" class="aui-card--fill">
        <div class="mod-oss__oss">
          <el-form :inline="true" :model="dataForm">   
            <el-form-item>
              <el-button type="primary" @click="approveVod()">视频点播</el-button>
            </el-form-item>
          </el-form>
          <video-vod v-if="videoVisibleVod" ref="videoVod" @my-event="getMyEvent" @refreshDataList="getDataList"></video-vod>
        </div>
      </el-card>
    </template>
    
    <script>
    import VideoVod from '../../../components/VideoPlayVod'
    export default {
      data () {
        return {
          mixinViewModuleOptions: {
            getDataListURL: '/oss/file/page',
            getDataListIsPage: true,
            deleteURL: '/oss/file',
            deleteIsBatch: true
          },
          dataForm: {},
          configVisible: false,
          uploadVisible: false,
          uploadVisibleVod: false,
          videoVisibleVod: false
        }
      },
      components: {
        Config,
        Upload,
        UploadVod,
        VideoVod
      },
      methods: {
        // 视频点播上传
        approveVod () {
          this.videoVisibleVod = true
          this.$nextTick(() => {
            this.$refs.videoVod.init('903d803f735e47c9aa12ef10721cb9a2')
          })
        },
        getMyEvent (vid) {
          console.log('接收的数据--------->' + vid)
          this.videoVisibleVod = false
        }
      }
    }
    </script>
    
    

    后台java开发的接口代码参照下篇博客,阿里云VOD 视频点播(三)

    阿里云VOD 视频点播(三)

  • 相关阅读:
    Power BI 根据用户权限动态生成导航跳转目标
    Power BI Tooltips 增强功能
    Power BI refresh error “could not load file or assembly…provided impersonation level is invalid”
    SQL 错误代码 18456
    如何使用SQL Server Integration Services从多个Excel文件读取数据
    通过表格编辑器将现有表引入Power BI数据流
    Power BI 中动态增长的柱状图
    ambari2.7.3离线安装hdp3.1.0时,ambari-hdp-1.repo中baseurl无值
    ambari 安装 cannot download file mysql-connector-java from http://8080/resource/mysql-connector-java.jar
    洛谷P4180 [BJWC2010]严格次小生成树
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13300582.html
Copyright © 2011-2022 走看看