Vue+java:阿里云OSS 实现视频上传,前端Vue使用vueMiniPlayer动态地址视频播放,以及发布时遇到aliyun-java-vod-upload时依赖报错问题的解决方法
视频上传功能首先,服务器需要开通视频点播的功能。我使用的java开发,阿里云官方文档地址:阿里云官方SDK示例(1)vue视频上传的<template><a-spin :spinning="confirmLoading"><j-form-container :disabled="formDisabled"><a-form-model ref="form"
·
1. 阿里云OSS视频上传功能
首先,服务器需要开通视频点播的功能。
我使用的java开发,阿里云官方文档地址:阿里云官方SDK示例
(1)vue视频上传的关键代码
<a-upload
name='file'
:headers='headers'
:multiple='false'
:action='uploadAction'
:file-list='fileList'
@change='handleChange'
:before-upload='beforeUpload'
:remove='doRemove'
>
<a-button>
<a-icon type='upload'/>
上传
</a-button>
</a-upload>
JS关键代码:
<script>
import {httpAction,uploadAction} from '@/api/manage'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'
export default {
name: 'VoteVideoForm',
components: {},
props: {},
data() {
return {
model: {
videoUrl: '',
},
uploadAction: window._CONFIG['domianURL'] + '/vote/voteVideo/uploadAlyiVideo',
fileList: []
}
},
methods: {
/**
* 选择文件
* @param info
* @returns {boolean}
*/
handleChange(info) {
if (info.file.status !== 'uploading') {
console.log('上传中')
}
if (info.file.status === 'done') {
console.log('完成', info.file)
}
if (info.file.status === 'error') {
console.log('失败', info.file)
}
return true
},
/**
* 上传文件
* @param file
* @returns {boolean}
*/
beforeUpload(file) {
//置空
let fileObj = {
uid: '-1',
name: file.name,
status: 'uploading',
url: ''
}
this.fileList = [fileObj]
let that = this
let formData = new FormData()
formData.append('file', file)
uploadAction(this.uploadAction, formData).then(res => {
if (res.success) {
// const data = JSON.parse(res.result)
const data = res.result
fileObj.status = 'done'
fileObj.url = 'videoUrl'
that.fileList = [fileObj]
that.model.videoUrl = data
} else {
fileObj.status = 'error'
that.fileList = [fileObj]
}
}).catch(err => {
fileObj.status = 'error'
that.fileList = [fileObj]
})
return false
},
/**
* 删除文件
* @param file
* @returns {boolean}
*/
doRemove() {
this.fileList = []
this.model.videoUrl = ''
return true
}
}
}
</script>
(2) java后端:可参考阿里云OSS官方文档
controller的完整方法:(顺带了通过videoId获取播放地址的方法)
//上传视频到阿里云 上传到的是默认地区:华东2(上海)
@AutoLog(value = "上传视频到阿里云 返回视频播放地址")
@ApiOperation(value = "上传视频到阿里云 返回视频播放地址", notes = "上传视频到阿里云 返回视频播放地址")
@PostMapping("/uploadAlyiVideo")
public Result uploadAlyiVideo(@RequestParam("file") MultipartFile file) {
Result result = new Result<>();
try {
log.info("\n【视频上传】 文件名:{} , 大小:{}", file.getOriginalFilename(), file.getSize() / 1024 < 1024 ? String.format("%sKB", file.getSize() / 1024) : String.format("%sMB", file.getSize() / 1024 / 1024));
//返回上传视频id 带到页面上作为视频对象的id
String videoId = voteVideoService.uploadVideoAly(file);
if (videoId != null) {
List<GetPlayInfoResponse.PlayInfo> list = (List<GetPlayInfoResponse.PlayInfo>) getPlayAuth(videoId).getResult();
//返回视频播放地址
String videoUrl = list.get(0).getPlayURL();
result.setResult(videoUrl);
result.setMessage(videoUrl.toString());
result.setSuccess(true);
log.info("\n【视频上传】 获取视频基础信息-视频地址 {}", videoUrl);
} else {
log.info("\n【视频上传】 上传失败");
result.setMessage("上传失败!");
result.setSuccess(false);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* 阿里云 根据视频id获取视频地址
*/
@AutoLog(value = "阿里云-根据视频id获取视频地址")
@ApiOperation(value = "阿里云-根据视频id获取视频地址", notes = "阿里云-根据视频id获取视频地址")
@GetMapping("/getPlayAuth")
public Result<?> getPlayAuth(@RequestParam(name = "id") String id) {
DefaultAcsClient client = initVodClient();
GetPlayInfoResponse response = new GetPlayInfoResponse();
List<GetPlayInfoResponse.PlayInfo> playInfoList = new ArrayList<>();
try {
response = getPlayInfo(client, id);
playInfoList = response.getPlayInfoList();
//播放地址
for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
System.out.print("播放地址 PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
}
//Base信息
System.out.print("标题 VideoBase.Title = " + response.getVideoBase().getTitle() + "\n");
} catch (Exception e) {
System.out.print("错误信息 ErrorMessage = " + e.getLocalizedMessage());
}
System.out.print("响应 RequestId = " + response.getRequestId() + "\n");
return Result.OK(playInfoList);
}
/*获取播放地址函数*/
public static GetPlayInfoResponse getPlayInfo(DefaultAcsClient client, String id) throws Exception {
GetPlayInfoRequest request = new GetPlayInfoRequest();
request.setVideoId(id);
return client.getAcsResponse(request);
}
@PostConstruct
public DefaultAcsClient initVodClient() {
try {
String regionId = "cn-shanghai"; // 点播服务接入区域
DefaultProfile profile = DefaultProfile.getProfile(regionId, ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
serviceImpl的完整方法:
/**
* 阿里云视频点播 上传
*
* @param file
* @return
*/
@Override
public String uploadVideoAly(MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
log.info("\n {} ", file.getOriginalFilename());
String title = fileName.substring(0, fileName.lastIndexOf("."));
InputStream inputStream = file.getInputStream();
UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadStreamResponse response = uploader.uploadStream(request);
String videoId = null;
if (response.isSuccess()) {
videoId = response.getVideoId();
} else {
videoId = response.getVideoId();
log.info(" ErrorCode: {}, ErrorMessage: {} ,VideoId: {}", new Object[] { response.getCode(), response.getMessage(), response.getVideoId() });
}
log.info("\n {} , videoId: {}", file.getOriginalFilename(), videoId);
return videoId;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
2. Vue 视频播放功能:使用vueMiniPlayer
vue-mini-player安装命令:
npm install vue-mini-player -S
完整的播放页面:vueMiniPlayer
使用阿里云的视频截帧功能给cover赋值:阿里云视频截帧功能文档
<template>
<div class="video_play">
<vueMiniPlayer
ref="vueMiniPlayer"
:video="video"
:mutex="true"
@fullscreen="handleFullscreen"
/>
</div>
</template>
<script>
import Vue from 'vue'
import vueMiniPlayer from 'vue-mini-player'
import 'vue-mini-player/lib/vue-mini-player.css'
Vue.use(vueMiniPlayer)
export default {
name: "myVidePlayer",
components: {
},
props: {
info:{ //这个就是父组件中子标签自定义名字
type:Object,
required:true
}
},
data() {
return {
video: {
url: this.info.videoUrl,
cover: this.info.videoUrl+"?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast",
muted: false, // 是否静音播放
loop: false, // 视频是否循环播放
preload: 'auto', // 视频预加载
poster: '', // 原生视频默认海报暂不设置
volume: 1, // 默认音量
autoplay: false, // 视频自动播放
}
}
},
watch: {},
mounted() {},
created: function () {},
methods: {
handleFullscreen() {}
}
}
</script>
<style scoped lang="less">
.video_play{
width: 100%;
height:100%;
}
</style>
引入播放的页面关键代码:使用v-bind使用数据传递
<template>
<div class="small_div" v-for="(item , index) in list" :key="index">
<div class="video_play">
<VideoPlayer v-bind:info="item"/>
</div>
</div>
</template>
<script>
import {getVoteActivity, getVotes, addVotesTicket} from "@/api/manage";
import VideoPlayer from '@/views/base/VideoPlayer'
import 'vue-mini-player/lib/vue-mini-player.css'
export default {
name: "BaseIndex",
components: {
VideoPlayer
},
data() {
return {
list: [],
}
},
mounted() {
this.getVotes();
},
methods: {
//获取视频列表
getVotes() {
const that = this
getVotes().then(res => {
//console.log("查询", res)
const result = res.result
that.list = result;
})
},
}
}
</script>
3. 打包过程中:aliyun-java-vod-upload依赖报错,需要使用本地依赖包
maven使用的阿里云仓库,setting中:
<mirror>
<id>aliyunmaven</id>
<name>阿里云公共仓库</name>
<mirrorOf>*</mirrorOf>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
设置本地仓库地址:【对应到自己的仓库地址】
<localRepository>D:\apache-maven-3.6.1-depository</localRepository>
将aliyun-java-vod-upload-1.4.14.jar执行加载到本地仓库,然后正常的使用package命令打包
cmd窗口运行以下命令:
mvn install:install-file -Dfile=aliyun-java-vod-upload-1.4.14.jar -DgroupId=com.aliyun -DartifactId=aliyun-java-vod-upload -Dversion=1.4.14 -Dpackaging=jar
实现过程参考了一些文档以及文章,以上可能会存在没记录到的地方,如果文章中存在问题,欢迎评论区指出。
更多推荐
已为社区贡献1条内容
所有评论(0)