一,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{
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>
(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>