1、引入依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.6.0</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>2.16.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-kms</artifactId>
<version>2.10.1</version>
</dependency>
2、初始化配置
#你自己的阿里云keyId
aliyun.vod.file.keyid=xxxxxxxxx
#你自己的阿里云密钥
aliyun.vod.file.keysecret=xxxxxxxxxx
#max-file-size 是单个文件大小
#max-request-size 是设置总上传的数据大小
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB
3、工具包
3.1、常量类
package com.zhmsky.vod.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author zhmsky
* @date 2022/4/29 17:22
*/
@Component
public class VodConstant implements InitializingBean {
@Value("${aliyun.vod.file.keyid}")
private String accessKeyId;
@Value("${aliyun.vod.file.keysecret}")
private String accessKeySecret;
public static String ACCESS_KEYID;
public static String ACCESS_KEYSECRET;
//在属性初始化后自动执行
@Override
public void afterPropertiesSet() throws Exception {
ACCESS_KEYID = accessKeyId;
ACCESS_KEYSECRET = accessKeySecret;
}
}
3.2、AccessKey初始化
package com.zhmsky.vod.utils;
import com.aliyun.oss.ClientException;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
/**
* @author zhmsky
* @date 2022/4/28 16:25
*/
public class InitVodClient {
//填入AccessKey信息
public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
String regionId = "cn-shanghai"; // 点播服务接入地域
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
}
4、阿里云视频点播服务(Vod)实现视频上传、删除
4.1、service(
package com.zhmsky.vod.service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* @author zhmsky
* @date 2022/4/29 16:58
*/
public interface VodService {
/**
* 上传本地文件至阿里云
* @return
*/
String uploadLocalVideoToAliYun(MultipartFile file);
/**
* 根据视频id删除阿里云视频
* @param videoId
*/
boolean removeVideo(String videoId);
/**
* 批量删除阿里云视频
* @param videoIdList
*/
boolean removeBatchVideo(List<String> videoIdList);
}
4.2 impl
package com.zhmsky.vod.service.impl;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.zhmsky.exception.MyException;
import com.zhmsky.vod.service.VodService;
import com.zhmsky.vod.utils.InitVodClient;
import com.zhmsky.vod.utils.VodConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @author zhmsky
* @date 2022/4/29 16:59
*/
@Service
public class VodServiceImpl implements VodService {
/**
* 上传本地视频文件至阿里云
* @return videoId 视频id
*/
@Override
public String uploadLocalVideoToAliYun(MultipartFile file) {
String accessKeyId= VodConstant.ACCESS_KEYID;
String accessKeySecret=VodConstant.ACCESS_KEYSECRET;
//获取文件原始名称
String fileName=file.getOriginalFilename();
String title=fileName.substring(0,fileName.lastIndexOf("."));
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, inputStream);
UploadVideoImpl uploader = new UploadVideoImpl();
UploadStreamResponse response = uploader.uploadStream(request);
String videoId="";
if (response.isSuccess()) {
videoId=response.getVideoId();
} else { //如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因
videoId=response.getVideoId();
}
return videoId;
}
/**
* @description 根据视频id删除阿里云视频
* @param videoId
*/
@Override
public boolean removeVideo(String videoId) {
//初始化对象
DefaultAcsClient client = InitVodClient.initVodClient(VodConstant.ACCESS_KEYID, VodConstant.ACCESS_KEYSECRET);
//创建删除视频的request对象
DeleteVideoRequest request = new DeleteVideoRequest();
//向request对象中设置视频id
request.setVideoIds(videoId);
//调用初始化对象的方法实现删除
try {
client.getAcsResponse(request);
return true;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
/**
* 批量删除阿里云视频
* @param videoIdList
*/
@Override
public boolean removeBatchVideo(List<String> videoIdList) {
String videoList = StringUtils.join(videoIdList.toArray(), ",");
//初始化对象
DefaultAcsClient client = InitVodClient.initVodClient(VodConstant.ACCESS_KEYID, VodConstant.ACCESS_KEYSECRET);
//创建删除视频的request对象
DeleteVideoRequest request = new DeleteVideoRequest();
//向request对象中设置视频id
request.setVideoIds(videoList);
//调用初始化对象的方法实现删除
try {
client.getAcsResponse(request);
return true;
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}
4.3、controller
package com.zhmsky.vod.controller;
import com.zhmsky.result.Result;
import com.zhmsky.result.ResultUtil;
import com.zhmsky.vod.service.VodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* @author zhmsky
* @date 2022/4/29 16:56
*/
@RestController
@RequestMapping("/eduVod/video")
@CrossOrigin
@Api("阿里云视频点播服务")
public class VodController {
@Autowired
private VodService vodService;
@PostMapping("/upload")
@ApiOperation("上传本地文件到阿里云")
public Result<String> uploadLocalVideo(MultipartFile file){
String videoId = vodService.uploadLocalVideoToAliYun(file);
return new ResultUtil<String>().setData(videoId);
}
@DeleteMapping("/deleteVideo/{videoId}")
@ApiOperation("删除阿里云视频——单个")
public Result<String> deleteVideoForAliYun(@PathVariable String videoId){
boolean b = vodService.removeVideo(videoId);
if(b){
return new ResultUtil<String>().setSuccessMsg("视频删除成功!");
}else{
return new ResultUtil<String>().setErrorMsg("视频删除失败!");
}
}
@ApiOperation("批量删除阿里云视频")
@DeleteMapping("/deleteBatchVideo")
public Result<String> deleteBatchVideo(@RequestParam("videoIdList") List<String> videoIdList){
boolean b = vodService.removeBatchVideo(videoIdList);
if(b){
return new ResultUtil<String>().setSuccessMsg("批量删除成功!");
}else {
return new ResultUtil<String>().setErrorMsg("批量删除失败!");
}
}
}
4.4、前端html
<el-form-item label="上传视频">
<el-upload
<!-- 上传成功过后执行 -->
:on-success="handleVodUploadSuccess"
<!-- 删除成功过后执行 -->
:on-remove="handleVodRemove"
:before-remove="beforeVodRemove"
<!-- 文件超过大小后执行 -->
:on-exceed="handleUploadExceed"
:file-list="fileList"
:action="BASE_API + '/eduVod/video/upload'"
:limit="1"
class="upload-demo"
>
<el-button size="small" type="primary">上传视频</el-button>
<el-tooltip placement="right-end">
<div slot="content">
最大支持1G,<br />
支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br />
GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br />
MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br />
SWF、TS、VOB、WMV、WEBM 等视频格式上传
</div>
<i class="el-icon-question" />
</el-tooltip>
</el-upload>
</el-form-item>
5、阿里云视频点播服务实现在线视频播放
5.1、service
/**
* 根据视频id获取视频的播放凭证
* @param videoId
* @return
*/
String getPlayRule(String videoId);
5.2、impl
/**
* 根据视频id获取视频的播放凭证
* @param videoId
* @return 视频播放凭证
*/
@Override
public String getPlayRule(String videoId) {
//创建对象
DefaultAcsClient client = InitVodClient.initVodClient(VodConstant.ACCESS_KEYID, VodConstant.ACCESS_KEYSECRET);
//获取视频凭证的request和response对象
GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
//向request设置videoId
request.setVideoId(videoId);
//调用初始化对象方法得到凭证
try {
response=client.getAcsResponse(request);
} catch (ClientException e) {
e.printStackTrace();
}
return response.getPlayAuth();
}
5.3 controller
@GetMapping("/getAliPlayRule/{videoId}")
@ApiOperation("根据视频id获取视频的播放凭证")
public Result<String> getAliPlayRule(@PathVariable String videoId){
String playRule = vodService.getPlayRule(videoId);
return new ResultUtil<String>().setData(playRule);
}
5.4、前端
<template>
<div>
<!-- 阿里云视频播放器样式 -->
<link rel="stylesheet" href="https://g.alicdn.com/de/prismplayer/2.8.1/skins/default/aliplayer-min.css" >
<!-- 阿里云视频播放器脚本 -->
<script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/de/prismplayer/2.8.1/aliplayer-min.js" />
<!-- 定义播放器dom -->
<div id="J_prismPlayer" class="prism-player" />
</div>
</template>
<script>
// 视频播放后端接口引入
import vedioApi from '@/api/vedio'
export default {
//应用video布局
layout: 'video',
//异步方式调用
asyncData({ params, error }) {
// params.vedioId等价于this.$route.params.vedioId(获取路径变量)
return vedioApi.getPlayRule(params.vedioId).then(response => {
return {
playAuth: response.data.result,
vid:params.vedioId
}
})
},
mounted(){
//页面渲染之后
new Aliplayer({
id: 'J_prismPlayer',
vid: this.vid, // 视频id
playauth: this.playAuth, // 播放凭证
encryptType: '1', // 如果播放加密视频,则需设置encryptType=1,非加密视频无需设置此项
width: '100%',
height: '500px',
// 以下可选设置
cover: 'http://guli.shop/photo/banner/1525939573202.jpg', // 设置视频封面
qualitySort: 'asc', // 清晰度排序
mediaType: 'video', // 返回音频还是视频
autoplay: false, // 自动播放
isLive: false, // 直播
rePlay: false, // 循环播放
preload: true,
controlBarVisibility: 'hover', // 控制条的显示方式:鼠标悬停
useH5Prism: true, // 播放器类型:html5
}, function(player) {
console.log('播放器创建成功')
})
}
}
</script>