一,nuxt視頻上傳,視頻播放
(1).nuxt視頻上傳,封裝的組件,我開發的時候有eslint校驗下面代碼有一些相關的註釋不用管
<template>
<div class="container">
<div class="upload">
<div>
<div class="filebox">
<input id="fileUpload" type="file" class="filebtn" @change="fileChange($event)">
<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" :disabled="uploadDisabled" @click="authUpload">
開始上傳
</el-button>
<el-button style="margin-left: 10px;" size="small" type="danger" :disabled="pauseDisabled" @click="pauseUpload">
暫停
</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'" />
</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() {
// eslint-disable-next-line no-console
console.log('-----1-----')
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
const userData = '{"Vod":{}}'
if (this.uploader) {
this.uploader.stopUpload()
this.authProgress = 0
this.statusText = ''
}
this.uploader = this.createUploader()
// eslint-disable-next-line no-console
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) {
const 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 = '添加文件成功, 等待上傳...'
// eslint-disable-next-line no-console
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) {
const title = uploadInfo.file.name.substr(0, uploadInfo.file.name.lastIndexOf('.'))
self.$axios.get('/api/ossFile/createUploadVideo', { params: { title: title, fileName: uploadInfo.file.name } }).then(({ data: res }) => {
if (res.code !== 0) {
return self.$message.error(res.msg)
}
const uploadAuth = res.data.UploadAuth
const uploadAddress = res.data.UploadAddress
const videoId = res.data.VideoId
self.vid = res.data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
})
self.statusText = '文件開始上傳...'
// eslint-disable-next-line no-console
console.log('onUploadStarted:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
} else {
// 如果videoId有值,根據videoId刷新上傳憑證
self.$axios.get('/api/ossFile/refreshUploadVideo', { params: { videoId: uploadInfo.videoId } }).then(({ data: res }) => {
if (res.code !== 0) {
return self.$message.error(res.msg)
}
const uploadAuth = res.data.UploadAuth
const uploadAddress = res.data.UploadAddress
const videoId = res.data.VideoId
self.vid = res.data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
})
}
},
// 文件上傳成功
onUploadSucceed: function (uploadInfo) {
// eslint-disable-next-line no-console
console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
self.statusText = '文件上傳成功!'
},
// 文件上傳失敗
onUploadFailed: function (uploadInfo, code, message) {
// eslint-disable-next-line no-console
console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message)
self.statusText = '文件上傳失敗!'
},
// 取消文件上傳
onUploadCanceled: function (uploadInfo, code, message) {
// eslint-disable-next-line no-console
console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message)
self.statusText = '文件已暫停上傳'
},
// 文件上傳進度,單位:字節, 可以在這個函數中拿到上傳進度並顯示在頁面上
onUploadProgress: function (uploadInfo, totalSize, progress) {
// eslint-disable-next-line no-console
console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%')
const 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.$axios.get('/api/ossFile/refreshUploadVideo', { params: { videoId: uploadInfo.videoId } }).then(({ data: res }) => {
if (res.code !== 0) {
return self.$message.error(res.msg)
}
const uploadAuth = res.data.UploadAuth
uploader.resumeUploadWithAuth(uploadAuth)
// eslint-disable-next-line no-console
console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
})
self.statusText = '文件超時...'
},
// 全部文件上傳結束
onUploadEnd: function (uploadInfo) {
// eslint-disable-next-line no-console
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{
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;
}
</style>
(2),nuxt引入阿里提供的上傳js文件,添加ssr:false服務端渲染關閉,因爲js裏面有document,window,服務端渲染會報錯undefined
(3),頁面調用封裝好的組件,裏面涉及到父子組件相互調用,傳值
<template>
<div>
<upload-vod ref="childVod" @my-event="getMyEvent" />
</div>
</template>
<script>
import UploadVod from '../../components/uploadvod'
export default {
components: {
UploadVod
},
data() {
return {
}
},
created() {
this.init()
},
methods: {
init() {
const that = this
if (process.client) {
that.$nextTick(() => {
that.$refs.childVod.emitEventVod()
})
}
},
getMyEvent(vid) {
// eslint-disable-next-line no-console
console.log('接收的數據--------->' + vid)
this.$message({
message: '接收的數據---->' + vid,
type: 'success'
})
}
}
}
</script>
(4),nuxt視頻播放相關,上傳根據官方提供的demo修改的,自己封裝了組件,引入的也是網絡js文件
<template>
<div :id="playerId" class="prism-player" />
</template>
<script>
export default {
props: {
aliplayerSdkPath: {
// Aliplayer 代碼的路徑
type: String,
default: '//g.alicdn.com/de/prismplayer/2.8.2/aliplayer-min.js'
}
},
data() {
return {
playerId: 'aliplayer_' + Math.random().toString(36).substr(2),
scriptTagStatus: 0,
isReload: false,
instance: null,
vid: '',
playauth: '',
cover: ''
}
},
created() {
this.init()
},
mounted() {
if (window.Aliplayer !== undefined) {
// 如果全局對象存在,說明編輯器代碼已經初始化完成,直接加載編輯器
this.scriptTagStatus = 2
this.initAliplayer()
} else {
// 如果全局對象不存在,說明編輯器代碼還沒有加載完成,需要加載編輯器代碼
this.insertScriptTag()
}
},
methods: {
async init() {
const { data } = await this.$axios.get('/api/ossFile/getVideoPlayAuth', { params: { videoId: '903d803f735e47c9aa12ef10721cb9a2' } })
// eslint-disable-next-line no-console
console.log('fetch---', data)
this.cover = data.data.CoverUrl
this.playauth = data.data.PlayAuth
this.vid = data.data.VideoId
// eslint-disable-next-line
if (window.Aliplayer !== undefined) {
// 如果全局對象存在,說明編輯器代碼已經初始化完成,直接加載編輯器
this.scriptTagStatus = 2
this.initAliplayer()
} else {
// 如果全局對象不存在,說明編輯器代碼還沒有加載完成,需要加載編輯器代碼
this.insertScriptTag()
}
},
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>
(5),將組件封裝爲一個插件js,然後引入js到nuxt中,以爲組件裏面有document,window,需要關閉ssr服務端渲染
import Vue from 'vue'
import AliplayerVod from '~/components/VideoPlayVod.vue'
Vue.component('ali-aliplayer-vod', AliplayerVod)
關閉ssr,如圖
(6),使用播放的組件
<ali-aliplayer-vod />