Vue+java:阿里云OSS 实现视频上传,前端Vue使用vueMiniPlayer动态地址视频播放,以及发布时遇到aliyun-java-vod-upload时依赖报错问题的解决方法
Posted 平芜尽处是春山-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue+java:阿里云OSS 实现视频上传,前端Vue使用vueMiniPlayer动态地址视频播放,以及发布时遇到aliyun-java-vod-upload时依赖报错问题的解决方法相关的知识,希望对你有一定的参考价值。
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
实现过程参考了一些文档以及文章,以上可能会存在没记录到的地方,如果文章中存在问题,欢迎评论区指出。
vue+Springboot上传oss阿里云并回显到前端页面
vue+Springboot上传图片到oss并回显
最近需要用到文件上传了,找了好多博客,最后总结了一下,记录一下操作。
1、前端代码
<!--文件上传弹出框-->
<el-button type="primary" round @click="uploadvisible=true">添加文件</el-button>
<!-- 表格显示图片 -->
<template>
<img :src="imgUrl" width="100px" height="100px"/>
</template>
<el-dialog
:visible.sync="uploadvisible"
>
<el-form>
<el-form-item label="文件" prop="file">
<el-input v-model="fileName" :disabled="true"></el-input>
<br>
<el-upload class="upload-demo"
ref=""
action=""
:limit="1"
:before-upload="beforeUpload">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传.jpg或者.png格式,且不超过5MB</div>
</el-upload>
<el-button @click="uploadvisible = false">取消</el-button>
<el-button type="primary" @click="submitUpload">确定</el-button>
</el-form-item>
</el-form>
</el-dialog>
1、2 js代码
data()
return
//文件名
fileName: "",
//上传弹出框的提示
uploadvisible: false,
//图片url
imgUrl: "",
,
methods:
//文件上传
//要在data中定义fileName和visible
//检查文件格式大小等
//上传文件校验
beforeUpload(file)
console.log(file, '文件');
this.files = file;
//只允许上传文件的格式
const extension = file.name.split('.')[1] === 'jpg'
const extension2 = file.name.split('.')[1] === 'png'
const isLt2M = file.size / 1024 / 1024 < 5
if (!extension && !extension2)
this.$message.warning('只能是 .jps、.png格式!')
return
if (!isLt2M)
this.$message.warning('大小不能超过 5MB!')
return
this.fileName = file.name;
return false // 返回false不会自动上传
,
//提交上传
submitUpload()
var that = this;
console.log('上传' + this.files.name)
if (this.fileName == "")
this.$message.warning('请选择要上传的文件!')
return false
let fileFormData = new FormData();
fileFormData.append('file', this.files, this.fileName);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名
let requestConfig =
headers:
//消息头
'Content-Type': 'multipart/form-data'
,
this.$http.post(`/back/car/uploadAvator`, fileFormData, requestConfig).then(response =>
//console.log(response.data.result);
that.$message.success(response.data.msg)
that.imgUrl = response.data.result;
//console.log(that.imgUrl)
//关闭弹框
that.uploadvisible = false;
)
,
2、 后端代码
- 导入依赖
<!--阿里云oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2、1 controller层
@RestController
@RequestMapping("/back/check")
@Api(tags="上传文件")
@CrossOrigin
public class CheckController
@Resource
private OssService ossService;
/**
* 上传头像到阿里云的oss
* CommonResult 这是工具类,没有可以使用map替代
*/
@PostMapping("uploadAvator")
public CommonResult uploadOssFile(@RequestParam("file") MultipartFile file)
System.out.println("file::"+file);
String url = ossService.uploadFileAvatar(file);
System.out.println("url::"+url);
return new CommonResult(2000,"文件上传成功",url);
2、2 service层
import org.springframework.web.multipart.MultipartFile;
public interface OssService
String uploadFileAvatar(MultipartFile file);
2、3impl层
package com.carrent.back.service.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.carrent.back.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService
@Override
public String uploadFileAvatar(MultipartFile file)
//上传的操作
//将文件的名字编程唯一的再上传
int i = file.getOriginalFilename().lastIndexOf(".");//获取上传的文件的原名
String suffix = file.getOriginalFilename().substring(i);
//System.out.println("fileanme文件原名:"+suffix);
//借助 UUID 将文件名编程唯一的 重新定义
String uuid = UUID.randomUUID().toString();
//定义上传oss的文件路径
String datePath = "vue";
String filename = datePath + "/" + uuid + suffix;
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
String accessKeyId = "xxxx";
String accessKeySecret = "xxxx";
String bucketName = "你的仓库名称";
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
String objectName = filename;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 上传文件到指定的存储空间(bucketName)并将其保存为指定的文件名称(objectName)。
try
//file.getInputStream() 当前文件的输入流
ossClient.putObject(bucketName, objectName, file.getInputStream());
catch (IOException e)
e.printStackTrace();
// 关闭OSSClient。
ossClient.shutdown();
//https://tutu-image.oss-cn-beijing.aliyuncs.com/19c55f39-a82a-427c-9e81-25081271de06.jpg
String url = "https://" + bucketName + "." + endpoint + "/" + filename;
return url;
以上是关于Vue+java:阿里云OSS 实现视频上传,前端Vue使用vueMiniPlayer动态地址视频播放,以及发布时遇到aliyun-java-vod-upload时依赖报错问题的解决方法的主要内容,如果未能解决你的问题,请参考以下文章
vue+Springboot上传oss阿里云并回显到前端页面
vue+Springboot上传oss阿里云并回显到前端页面
vue+Springboot上传oss阿里云并回显到前端页面
SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后端篇: 整合阿里云 OSS 服务 -- 上传下载文件图片