当前位置:   article > 正文

阿里云视频点播 批量上传_vue 上传阿里点播

vue 上传阿里点播

   

    记录我惨痛的阿里云视频点播批量上传教训~~(Javascript SDK 上传)
    阿里的点播视频上传官方文档是很精简,也有案例,无奈我这个渣渣看了官方文档始终不理解它的内部机制。看了好多案例,自己捣鼓了无数遍,今天下午终于成功了。


      1.首先,我要总结一下我一开始不理解的批量上传:
        官方文档中给我们提供了一个uploader.addFile函数,这个函数的作用是将我们在input选择框中一次性选中的多个视频文件添加到视频点播实例化对象=>uploader的上传列表中。
        然后,我们通过自己设置的一个button触发uploader的startUpload(开始上传)事件。重点来了:
        触发startUpload事件后,进入了文档列举的onUploadstarted状态中,在这里我们通过uploadInfo 获取到视频文件列表中第一个文件的file,file.name,  通过判断当前的文件的videoId是否存在,去确定是否要重新获取视频上传凭证。
     视频上传凭证获取成功以后,就会自动进入到 onUploadProgress、onUploadSucceed或者其他状态进程中。
     当视频列表中的第一个视频文件上传成功后,uploader会自动选中下一个视频文件进行上传。当视频列表的所有文件上传成功以后,会进入到onUploadEnd状态进程中,表明列表中所有文件上传成功。
       (原来通过控制台打印,我始终只能看到一个视频文件,而不是文件列表,我还一直在纠结怎么在第一个文件上传成功以后去上传第二个视频文件,甚至还傻乎乎的去触发了第二次startUpload,结果就是直接提示xxx is experied-->进程已经开始或者过期);


      2.  第二个坑:通过addFile添加文件到列表成功,点击按钮触发startUpload事件,在onUploadstarted触发后台获取视频上传凭证接口并拿到了uploadAuth, uploadAdress,并进行设置。 但是,死活都不显示进入onProgress中的上传百分比。
代码如下:

  1. onUploadstarted: function (uploadInfo) {
  2.                 //获取文件上传列表
  3.                 that.uploader.listFiles();
  4.                 var list = that.uploader.listFiles();
  5.                 for (var i=0; i<list.length; i++) {
  6.                     console.log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
  7.                 }
  8.                 if (!uploadInfo.videoId) {
  9.                     var fileName = uploadInfo.file.name
  10.                     var title = that.title
  11.         //后台获取视频上传凭证接口
  12.                      that.auth(fileName, title)
  13.                     that.uploader.setUploadAuthAndAddress(uploadInfo, that.uploadAuth,  that.uploadAddress, that.videoId );
  14.                     console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  15.                         + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  16.                 } else {
  17.                     var fileName = uploadInfo.file.name
  18.                     var title = that.title
  19.                    //获取视频上传凭证
  20.                      that.auth(fileName, title)
  21.                     console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  22.                         + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  23.                 }
  24.             },

获取视频上传凭证方法(后端接口获取,得到的结果是uploadAuth、uploadAddress、videoId)

  1. auth(fileName, title){
  2.                   let param = new FormData()
  3.                   param.append("file_name",fileName)
  4.                   param.append("title",title)
  5.                   param.append("types", 1)     //接口必传参数
  6.                   this.$http.post("back/get_ali_video_token/", param).then((response)=>{
  7.                           console.log("返回的数据", response.data.data)
  8.                          this.uploadAuth = response.data.data.UploadAuth;
  9.                          this.uploadAddress = response.data.data.UploadAddress;
  10.                          this.videoId = response.data.data.VideoId;
  11.                 }).catch(function(error){
  12.                        console.log(error);
  13.                   })
  14.           },

无论是将 setUploadAuthAndAddress(uploadInfo, that.uploadAuth,  that.uploadAddress, that.videoId )写在auth方法中还是写在 onUploadstarted方法中,都无法正常进入 onUploadProgress中,通过控制台数据打印,发现

 console.log("返回的数据", response.data.data)   //打印从后端获取到的uploadAuth、uploadAdress等信息

在 setUploadAuthAndAddress后出现了,我感觉应该是异步执行的问题,证明uploadAuth、uploadAddress、videoId还是没有设置到uploader中,所以才导致上传失败。


3. 解决方法:直接把auth方法中的内容抽出放在onUploadstarted中:
    

  1. onUploadstarted: function (uploadInfo) {
  2. // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
  3. // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress
  4. // 如果 uploadInfo.videoId 有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口
  5. // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
  6. // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
  7. // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
  8. //获取文件上传列表
  9. that.uploader.listFiles();
  10. var list = that.uploader.listFiles();
  11. for (var i=0; i<list.length; i++) {
  12. console.log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
  13. }
  14. if (!uploadInfo.videoId) {
  15. var fileName = uploadInfo.file.name
  16. var title = that.title
  17. //获取上传凭证和地址
  18. let param = new FormData()
  19. param.append("file_name",fileName)
  20. param.append("title",title)
  21. // param.append("types", 1)
  22. that.$http.post("back/get_ali_video_token/",param
  23. ).then((response)=>{
  24. console.log("返回信息", response)
  25. let uploadAuth = response.data.data.UploadAuth;
  26. let uploadAddress = response.data.data.UploadAddress;
  27. let videoId = response.data.data.VideoId;
  28. that.uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  29. }).catch(function(error){
  30. console.log(error);
  31. })
  32. console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  33. + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  34. } else {
  35. /*
  36. // 如果videoId有值,根据videoId刷新上传凭证
  37. var refreshUrl = 'https://localhost:44325/vod/IRefreshUploadVideo?videoId=' + uploadInfo.videoId
  38. var fileName = uploadInfo.file.name
  39. //自定义上传接口
  40. //afaf8aa3d3e2489fb55a5601f076d3d1这里会莫名多出一个id,由于时间问题,所以这边我直接调用了视频接口,没有调用刷新凭证接口
  41. var createUrl = 'https://localhost:44325/vod/ICreateUploadVideo?title=' + fileName + '&fileName=' + fileName
  42. $.get(createUrl, function (data) {
  43. var uploadAuth = data.uploadAuth
  44. var uploadAddress = data.uploadAddress
  45. var videoId = data.videoId
  46. uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  47. }, 'json')
  48. */
  49. var fileName = uploadInfo.file.name
  50. var title = that.title
  51. //获取上传凭证和地址
  52. let param = new FormData()
  53. param.append("file_name",fileName)
  54. param.append("title",title)
  55. //param.append("types", 1) //该接口需要传的参数
  56. that.$http.post("back/get_ali_video_token/",param
  57. ).then((response)=>{
  58. console.log("返回信息", response)
  59. let uploadAuth = response.data.data.UploadAuth;
  60. let uploadAddress = response.data.data.UploadAddress;
  61. let videoId = response.data.data.VideoId;
  62. that.uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  63. }).catch(function(error){
  64. console.log(error);
  65. })
  66. console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  67. + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  68. }
  69. },


这样便可以正确的将当前视频文件的上传凭证等信息正确设置了,上传进程也能够正确进行了。

4. 还有一个小提示,当前上传进程开始后,我们应该禁用触发startUpload事件的按钮,避免上传报错的发生~~
以下是完整代码(使用结构是Vue):
               (1)上传视频入口

  1. <el-dialog title="视频上传" :visible.sync="createVideoChange(控制该窗口的显示)" :close-on-click-modal="false">
  2. 视频上传:
  3. <input type="file" multiple accept=".mp4" ref="clearFile" id="files" @change="triggerFile($event)"/>
  4. <el-button size="small" type="primary" style="margin:10px 0 0 0;" @click="uploadVideo" :disabled="onPro">开始上传</el-button><br/>
  5. {{this.file}}<el-progress :stroke-width="2" :percentage="this.progressNum" style="margin-top:5px; width: 500px;"></el-progress>
  6. <br />
  7. <br />
  8. <span slot="footer">
  9. <el-button @click="closeUploadVideo">取 消</el-button>
  10. <el-button type="primary" @click="closeUploadVideo">确定</el-button>
  11. </span>
  12. </el-dialog>


              (2)相关参数

  1. data(){
  2. return {
  3. uploader: null, //点播实例
  4. progressNum: 0, //进度条
  5. file: '', //当前上传的文件名
  6. uploadAuth: '', //点播信息
  7. uploadAddress: '',
  8. videoId: '',
  9. }
  10. }


              (3)选择视频文件

  1. triggerFile(event){
  2. this.efile = event
  3. console.log("文件上传列表", this.efile)
  4. //开始上传视频
  5. this.startUploadVideo(event)
  6. },
  7. //开始上传视频
  8. startUploadVideo(file){
  9. if(!file){
  10. return this.$message.warning("选择需要上传的视频!")
  11. }
  12. var userData = '{"Vod":{}}'
  13. //当前已经存在uploader 则暂停上传
  14. if(this.uploader){
  15. this.uploader.stopUpload()
  16. this.progressNum = 0;
  17. }
  18. //初始化实例 不存在uploader实例就要初始化
  19. this.uploader = this.Origin()
  20. // 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)
  21. //批量添加文件上传 标题为素材id+时间戳+当前视频id
  22. for (var i = 0; i < file.target.files.length; i++) {
  23. this.uploader.addFile(file.target.files[i], null, null, null, userData)
  24. //上传标题名为文件名
  25. this.title = this.materialId + '-' + file.target.files[i].name
  26. }
  27. },


              (4)创建点播实例

  1. Origin() {
  2. let that = this
  3. var uploader = new AliyunUpload.Vod({
  4. timeout: 90000,
  5. partSize: 1048576,
  6. parallel: that.efile.target.files.length,//文件多少,就设置多少
  7. retryCount: 3,
  8. retryDuration: 2,
  9. region: '',
  10. userId: that.userId,
  11. // 添加文件成功
  12. addFileSuccess: function (uploadInfo) {
  13. console.log('addFileSuccess', uploadInfo)
  14. console.log("添加文件名addFileSuccess: " + uploadInfo.file.name)
  15. },
  16. onUploadstarted: function (uploadInfo) {
  17. // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
  18. // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress
  19. // 如果 uploadInfo.videoId 有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口
  20. // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
  21. // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
  22. // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
  23. //获取文件上传列表
  24. that.uploader.listFiles();
  25. var list = that.uploader.listFiles();
  26. for (var i=0; i<list.length; i++) {
  27. console.log("file:" + list[i].file.name + ", status:" + list[i].state + ", endpoint:" + list[i].endpoint + ", bucket:" + list[i].bucket + ", object:" + list[i].object);
  28. }
  29. if (!uploadInfo.videoId) {
  30. var fileName = uploadInfo.file.name
  31. var title = that.title
  32. //获取上传凭证和地址
  33. let param = new FormData()
  34. param.append("file_name",fileName)
  35. param.append("title",title)
  36. param.append("types", 1) //创客代理
  37. that.$http.post("back/get_ali_video_token/",param
  38. ).then((response)=>{
  39. console.log("返回信息", response)
  40. let uploadAuth = response.data.data.UploadAuth;
  41. let uploadAddress = response.data.data.UploadAddress;
  42. let videoId = response.data.data.VideoId;
  43. that.uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  44. }).catch(function(error){
  45. console.log(error);
  46. })
  47. console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  48. + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  49. } else {
  50. /*
  51. // 如果videoId有值,根据videoId刷新上传凭证
  52. var refreshUrl = 'https://localhost:44325/vod/IRefreshUploadVideo?videoId=' + uploadInfo.videoId
  53. var fileName = uploadInfo.file.name
  54. //自定义上传接口
  55. //afaf8aa3d3e2489fb55a5601f076d3d1这里会莫名多出一个id,由于时间问题,所以这边我直接调用了视频接口,没有调用刷新凭证接口
  56. var createUrl = 'https://localhost:44325/vod/ICreateUploadVideo?title=' + fileName + '&fileName=' + fileName
  57. $.get(createUrl, function (data) {
  58. var uploadAuth = data.uploadAuth
  59. var uploadAddress = data.uploadAddress
  60. var videoId = data.videoId
  61. uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  62. }, 'json')
  63. */
  64. var fileName = uploadInfo.file.name
  65. var title = that.title
  66. //获取上传凭证和地址
  67. let param = new FormData()
  68. param.append("file_name",fileName)
  69. param.append("title",title)
  70. param.append("types", 1) //创客代理
  71. that.$http.post("back/get_ali_video_token/",param
  72. ).then((response)=>{
  73. console.log("返回信息", response)
  74. let uploadAuth = response.data.data.UploadAuth;
  75. let uploadAddress = response.data.data.UploadAddress;
  76. let videoId = response.data.data.VideoId;
  77. that.uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
  78. }).catch(function(error){
  79. console.log(error);
  80. })
  81. console.log("onUploadStarted:" + uploadInfo.file.name + ", uploadAuth:" + uploadInfo.uploadAuth + ", uploadAddress:" + uploadInfo.uploadAddress
  82. + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  83. }
  84. },
  85. // 文件上传成功
  86. onUploadSucceed: function (uploadInfo) {
  87. // that.$message.success(uploadInfo.file.name+ "上传成功!两分钟内自动上线")
  88. console.log("文件1上传成功的videoID", uploadInfo.videoId)
  89. that.file = uploadInfo.file.name
  90. that.video_id = uploadInfo.videoId
  91. that.createVideo()
  92. console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
  93. },
  94. // 文件上传失败
  95. onUploadFailed: function (uploadInfo, code, message) {
  96. that.$message.error(uploadInfo.file.name + "上传失败,请从当前视频开始重新上传")
  97. console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
  98. },
  99. // 取消文件上传
  100. onUploadCanceled: function (uploadInfo, code, message) {
  101. console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
  102. },
  103. // 文件上传进度,单位:字节, 可以在这个函数中拿到上传进度并显示在页面上
  104. onUploadProgress: function (uploadInfo, totalSize, progress) {
  105. that.onPro = true
  106. console.log("正在上传中")
  107. that.file = uploadInfo.file.name
  108. that.progressNum = (progress * 100).toFixed(2)
  109. console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
  110. },
  111. // 上传凭证超时
  112. onUploadTokenExpired: function (uploadInfo) {
  113. // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
  114. // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
  115. // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
  116. console.log('文件上传超时!')
  117. },
  118. // 全部文件上传结束
  119. onUploadEnd: function (uploadInfo) {
  120. console.log("onUploadEnd: uploaded all the files")
  121. that.$message.success("所有视频上传成功!")
  122. }
  123. })
  124. return uploader
  125. },


              (5)点击按钮开始上传视频

  1. //tt 确认视频上传按钮 标题和文件名不为空 初始化进程
  2. uploadVideo(){
  3. //点击上传视频,实例不为空 则开始上传
  4. if(this.uploader !== null){
  5. this.uploader.startUpload();
  6. }
  7. },


       视频点播,虽然官方文档描述真的挺清晰的,但是理解存在偏差就要钻牛角尖了,而且还没那么容易出来~~~~
在此需要感谢@孤独wind小白博主写的文章,从他那里我得到很多启发,原文链接:
https://www.jianshu.com/p/eb0b9c92ee71
            感谢查看我的文章,可能描述的不是那么清晰,欢迎提出意见或者进行交流,共同进步,感谢

           果然还是CSDN的编辑器给力~~用起来舒服

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/246000
推荐阅读
相关标签
  

闽ICP备14008679号