vue.js+element-UI+阿里云点播之视频上传(走前端)

一、阿里视频上传SDK下载

image

二、JS文件引入

image

三、代码块(只需要把上传凭证换成你自己的就行了)

1.html代码

<template>
  <div class="container">
    <div class="upload">
      <el-row>
        <el-col :span="5">
          <div class="filebox">
            <input type="file" id="fileUpload" @change="fileChange($event)" ref="referenceUpload" class="filebtn">
              <div class="flletit">选择视频</div>
            <div class="filetitle">{{fileTitle}}</div>
          </div>
        </el-col>
        <!-- <el-col :span="10">

        </el-col> -->
        <el-col :span="4">
          <el-button  size="small" type="danger" @click="pauseUpload" :disabled="pauseDisabled">暂停</el-button>
       </el-col>
       <el-col :span="4">
          <el-button size="small" type="primary"  @click="authUpload" :disabled="uploadDisabled">开始上传</el-button>
       </el-col>
       <el-col :span="4" :push="1">
         <el-button  size="small" type="success"  :disabled="resumeDisabled" @click="resumeUpload">恢复上传</el-button>
       </el-col>
      </el-row>
      <el-row >
        <el-col :span="24">
          <label class="status"><span class="span_status" style="color:#585858"></span> <span id="statusText">{{statusText}}</span></label>
        </el-col>
        <el-col :span="24">
          <el-progress id="progress" style="margin-left: 10px;"
           :text-inside="true" :stroke-width="15" :percentage='authProgress'
           :status='authProgress == 100 ? "success":"text"'>
           </el-progress>
        </el-col>

        <el-col :span="24">
          <!--用于计算视频时长-->
          <audio id="audio_id" hidden controls autoplay loop>Your browser can't support HTML5 Audio</audio>
        </el-col>

      </el-row>
    </div>
  </div>
</template>

2.JS代码

<script>
  //引入获取凭证js方法
  import {uploadV,refreshVideo} from '@/api/media/video/video'
 export default {
   props:["videoUrl","olvVideoId"],
   name:"myVideo",
  data () {
    return {
      //用于父组件传值
      vid: {
        videoUrl:this.videoUrl,
        videoSourceId:'',
        videoTime:0.0
      },
      //文件上传参数,及按钮进度条参数
      fileTitle: '',
      timeout: '',
      partSize: '',
      parallel: '',
      retryCount: '',
      retryDuration: '',
      region: '上传到点播的地域',
      userId: '阿里账号ID',
      file: null,
      authProgress: 0,
      uploadDisabled:true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: ''
    }
  },
  methods: {
    emitEventVod () {
      this.param.authProgress = 0
      this.fileTitle = ''
      this.statusText = ''
      this.pauseDisabled = true
      this.resumeDisabled = true
      this.uploadDisabled = true
    },
    millisecondToDate(msd) {
              // var time2 = parseFloat(msd) / 1000;
          var time = parseFloat(msd);//先将毫秒转化成秒
           var theTime = parseInt(msd);// 秒
              var middle= 0;// 分
              var hour= 0;// 小时
              if(theTime > 60) {
                  middle= parseInt(theTime/60);
                  theTime = parseInt(theTime%60);
                  if(middle> 60) {
                      hour= parseInt(middle/60);
                      middle= parseInt(middle%60);
                  }
              }
                var result = ''
              if(parseInt(theTime)>=10){
              result = "0"+":"+parseInt(theTime);
              }else{
              result = "0"+":"+"0"+parseInt(theTime);
              }
                  if(middle >= 0 && parseInt(theTime)>=10) {
                      result = parseInt(middle)+":"+parseInt(theTime);
                  }else{
                  result = parseInt(middle)+":"+"0"+parseInt(theTime);
              }
          return result;
      },
     onInputFileChange(file) {
            var url = URL.createObjectURL(file);

            var videos =document.getElementById("audio_id")
            videos.src = url;
            var that=this;
            setTimeout(function(){
            if(videos.readyState>0){
              var minutes = parseInt(videos.duration / 60, 10);
              var seconds = videos.duration % 60;
              var a=that.millisecondToDate(videos.duration);
            }

            },500)
        },

    fileChange (e) {
      this.file = e.target.files[0]
      var a=this.onInputFileChange(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.param.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('.'))
            //获取凭证的方法
            uploadV(title).then(({ data: res }) => {
              if (res.code !== 0) {
                // return self.$message.error(res.msg)
              }
              let uploadAuth = res.UploadAuth;
              let uploadAddress = res.UploadAddress;
              let videoId = res.VideoId;
              self.vid.videoSourceId = res.VideoId;
              self.vid.videoUrl=res.videoUrl;
              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刷新上传凭证
            refreshVideo({ videoId: uploadInfo.videoId}).then(res => {
              // if (res.data.code != 0) {
              //   return self.$message.error(res.data.msg)
              // }
              let uploadAuth = res.data.UploadAuth;
              let uploadAddress = res.data.UploadAddress;
              let videoId = res.data.VideoId;
              self.vid.videoSourceId = res.data.VideoId;
              self.vid.videoUrl=res.data.videoUrl;
              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 = parseInt(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)
    },
    //初始化组件参数方法
    initUploadData(){
     this.vid={
       videoUrl:'',
       videoSourceId:''
     },
     this.fileTitle= '',
     this.timeout= '',
     this.partSize= '',
     this.parallel= '',
     this.retryCount= '',
     this.retryDuration= '',
     this.region='cn-shanghai',
     this.userId='阿里账号ID',
     this.file=undefined,
     this.authProgress= 0,
     this.uploadDisabled=true,
     this.resumeDisabled= true,
     this.pauseDisabled=true,
     this.uploader=null,
     this.statusText= ''
     this.$refs.referenceUpload.value = null;
    }
  },
}
</script>

3.CSS代码

  .container{
    text-align: center;
    line-height: 1;
  }
  .upload-type{
    margin: 15px 0;
  }
  .filebox{
    width: 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{
width: 100%;
    height: 100%;
    border: none;
    background: none;
    position: absolute;
    left: 0;
    top: 0;
    opacity: 0;

  }
 .filebox .flletit{
   width: 100%;
   height: 100%;
 }
  .filetitle{
    margin: 10px 0;
  }
  .status span{
    color: #FF4C52;
  }
  .status{
    line-height: 28px;
  }
  .span_status{
    color:#000000;
    float:left;
    margin-left: 10px;
  }
  #progress{
  width: 450px;
  margin-left: 32px;
  }

四、JAVA后端获取凭证(其他语言请参考阿里云API)

点我获取前端上传凭证:https://www.jianshu.com/p/4693ffc5fec9

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容