SpringBoot+阿里云OSS实现在线视频播放的示例
阿里云 oss 是一种云存储技术,你可以理解为云盘,我们的目标是将视频存储到云端,然后在前端读取并播放视频。
oss
首先登陆首页,创建一个存储桶:
然后找到读写权限:
将读写权限设置为公共读即可:
在 ram 中新建一个用户:
为其添加权限,选择 oss 的权限:
然后点进去这个用户,找到 accesskey:
创建之后记下来 secret
,因为他只出现一次,如果没记住也没事,可以重新创建新的 key
。
下面开始编写服务端代码:
pom
<!-- 阿里云oss --> <dependency> <groupid>com.aliyun.oss</groupid> <artifactid>aliyun-sdk-oss</artifactid> <version>3.10.2</version> </dependency>
package com.lsu.file.controller.admin; import com.alibaba.fastjson.jsonobject; import com.aliyun.oss.oss; import com.aliyun.oss.ossclientbuilder; import com.aliyun.oss.model.appendobjectrequest; import com.aliyun.oss.model.appendobjectresult; import com.aliyun.oss.model.objectmetadata; import com.aliyun.oss.model.putobjectrequest; import com.lsu.server.dto.filedto; import com.lsu.server.dto.responsedto; import com.lsu.server.enums.fileuseenum; import com.lsu.server.service.fileservice; import com.lsu.server.util.base64tomultipartfile; import com.lsu.server.util.uuidutil; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.value; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.multipartfile; import javax.annotation.resource; import java.io.bytearrayinputstream; /** * @author wsuo */ @restcontroller @requestmapping("/admin") public class osscontroller { private static final logger log = loggerfactory.getlogger(filecontroller.class); @value("${oss.accesskeyid}") private string accesskeyid; @value("${oss.accesskeysecret}") private string accesskeysecret; @value("${oss.endpoint}") private string endpoint; @value("${oss.bucket}") private string bucket; @value("${oss.domain}") private string ossdomain; public static final string business_name = "oss文件上传"; @resource private fileservice fileservice; @postmapping("/oss-append") public responsedto<filedto> fileupload(@requestbody filedto filedto) throws exception { log.info("上传文件开始"); string use = filedto.getuse(); string key = filedto.getkey(); string suffix = filedto.getsuffix(); integer shardindex = filedto.getshardindex(); integer shardsize = filedto.getshardsize(); string shardbase64 = filedto.getshard(); multipartfile shard = base64tomultipartfile.base64tomultipart(shardbase64); fileuseenum useenum = fileuseenum.getbycode(use); string dir = useenum.name().tolowercase(); string path = dir + "/" + key + "." + suffix; // 创建ossclient实例。 oss ossclient = new ossclientbuilder().build(endpoint, accesskeyid, accesskeysecret); objectmetadata meta = new objectmetadata(); // 指定上传的内容类型。 meta.setcontenttype("text/plain"); // 通过appendobjectrequest设置多个参数。 appendobjectrequest appendobjectrequest = new appendobjectrequest(bucket, path, new bytearrayinputstream(shard.getbytes()), meta); appendobjectrequest.setposition((long) ((shardindex - 1) * shardsize)); appendobjectresult appendobjectresult = ossclient.appendobject(appendobjectrequest); // 文件的64位crc值。此值根据ecma-182标准计算得出。 system.out.println(appendobjectresult.getobjectcrc()); system.out.println(jsonobject.tojsonstring(appendobjectresult)); ossclient.shutdown(); log.info("保存文件记录开始"); filedto.setpath(path); fileservice.save(filedto); responsedto<filedto> responsedto = new responsedto<>(); filedto.setpath(ossdomain + path); responsedto.setcontent(filedto); return responsedto; } @postmapping("/oss-simple") public responsedto<filedto> fileupload(@requestparam multipartfile file, string use) throws exception { log.info("上传文件开始"); fileuseenum useenum = fileuseenum.getbycode(use); string key = uuidutil.getshortuuid(); string filename = file.getoriginalfilename(); string suffix = filename.substring(filename.lastindexof(".") + 1).tolowercase(); string dir = useenum.name().tolowercase(); string path = dir + "/" + key + "." + suffix; // 创建ossclient实例。 oss ossclient = new ossclientbuilder().build(endpoint, accesskeyid, accesskeysecret); putobjectrequest putobjectrequest = new putobjectrequest(bucket, path, new bytearrayinputstream(file.getbytes())); ossclient.putobject(putobjectrequest); responsedto<filedto> responsedto = new responsedto<>(); filedto filedto = new filedto(); filedto.setpath(ossdomain + path); responsedto.setcontent(filedto); return responsedto; } }
这部分内容可以参考阿里云的帮助手册:https://help.aliyun.com/document_detail/32011.html?spm=a2c4g.11174283.6.915.443b7da2mfhbkq
上面写的是两个接口:
- 追加上传:
/oss-append
- 简单上传:
/oss-simple
注意这里的参数都已经在 yml
文件中定义了:
上面的 keyid 和 keysecret 就是之前在创建用户时给的那两个,填上就行了。
在前端我们就可以发送请求获取数据,注意这里的对象是我自定义的,大家可以根据项目需求自行设置。
_this.$ajax.post(process.env.vue_app_server + '/file/admin/oss-simple', formdata).then(response => { loading.hide(); let resp = response.data; _this.afterupload(resp); // 清空原来控件中的值 $("#" + _this.inputid + "-input").val(""); })
视频点播
vod 是另一种视频存储的形式,它的功能更丰。阿里云视频点播(vod)是集音视频上传、自动化转码处理、媒体资源管理、分发加速于一体的全链路音视频点播服务。
我们同样需要一个 vod 的用户,给它赋予 vod 的权限:
sdk 的使用可以参考文档:https://help.aliyun.com/document_detail/61063.html?spm=a2c4g.11186623.6.921.418f192btdcijn
我们可以在转码组设置自己的模板,然后通过 id 在代码中使用:
上传视频比较简单,和 oss 很像,但是播放视频要多一个条件,在获取播放链接之前要先取得权限认证,所以下面单独写了一个 /get-auth/{vod}
接口,其中的参数就是 vod 的 id,这个 id 在我们上传视频之后会作为返回值返回的。
package com.lsu.file.controller.admin; import com.alibaba.fastjson.json; import com.alibaba.fastjson.jsonobject; import com.aliyun.oss.ossclient; import com.aliyuncs.defaultacsclient; import com.aliyuncs.vod.model.v20170321.createuploadvideoresponse; import com.aliyuncs.vod.model.v20170321.getmezzanineinforesponse; import com.aliyuncs.vod.model.v20170321.getvideoplayauthresponse; import com.lsu.server.dto.filedto; import com.lsu.server.dto.responsedto; import com.lsu.server.enums.fileuseenum; import com.lsu.server.service.fileservice; import com.lsu.server.util.base64tomultipartfile; import com.lsu.server.util.vodutil; import org.apache.commons.codec.binary.base64; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.value; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.multipartfile; import javax.annotation.resource; /** * @author wsuo */ @restcontroller @requestmapping("/admin") public class vodcontroller { private static final logger log = loggerfactory.getlogger(filecontroller.class); @value("${vod.accesskeyid}") private string accesskeyid; @value("${vod.accesskeysecret}") private string accesskeysecret; public static final string business_name = "vod视频上传"; @resource private fileservice fileservice; @postmapping("/vod") public responsedto<filedto> fileupload(@requestbody filedto filedto) throws exception { string use = filedto.getuse(); string key = filedto.getkey(); string suffix = filedto.getsuffix(); integer shardindex = filedto.getshardindex(); integer shardsize = filedto.getshardsize(); string shardbase64 = filedto.getshard(); multipartfile shard = base64tomultipartfile.base64tomultipart(shardbase64); fileuseenum useenum = fileuseenum.getbycode(use); string dir = useenum.name().tolowercase(); string path = dir + "/" + key + "." + suffix; //需要上传到vod的本地视频文件的完整路径,需要包含文件扩展名 string vod = ""; string fileurl = ""; try { // 初始化vod客户端并获取上传地址和凭证 defaultacsclient vodclient = vodutil.initvodclient(accesskeyid, accesskeysecret); createuploadvideoresponse createuploadvideoresponse = vodutil.createuploadvideo(vodclient, path); // 执行成功会返回videoid、uploadaddress和uploadauth vod = createuploadvideoresponse.getvideoid(); jsonobject uploadauth = jsonobject.parseobject( base64.decodebase64(createuploadvideoresponse.getuploadauth()), jsonobject.class); jsonobject uploadaddress = jsonobject.parseobject( base64.decodebase64(createuploadvideoresponse.getuploadaddress()), jsonobject.class); // 使用uploadauth和uploadaddress初始化oss客户端 ossclient ossclient = vodutil.initossclient(uploadauth, uploadaddress); // 上传文件,注意是同步上传会阻塞等待,耗时与文件大小和网络上行带宽有关 if (shard != null) { vodutil.uploadlocalfile(ossclient, uploadaddress, shard.getinputstream()); } system.out.println("上传视频成功, vod : " + vod); getmezzanineinforesponse response = vodutil.getmezzanineinforesponse(vodclient, vod); system.out.println("获取视频信息 response = " + json.tojsonstring(response)); fileurl = response.getmezzanine().getfileurl(); ossclient.shutdown(); } catch (exception e) { system.out.println("上传视频失败, errormessage : " + e.getlocalizedmessage()); } filedto.setpath(path); filedto.setvod(vod); fileservice.save(filedto); responsedto<filedto> responsedto = new responsedto<>(); filedto.setpath(fileurl); responsedto.setcontent(filedto); return responsedto; } @requestmapping(value = "/get-auth/{vod}", method = requestmethod.get) public responsedto<string> getauth(@pathvariable string vod) { log.info("获取播放授权开始"); responsedto<string> responsedto = new responsedto<>(); defaultacsclient client = vodutil.initvodclient(accesskeyid, accesskeysecret); getvideoplayauthresponse response; try { response = vodutil.getvideoplayauthresponse(client, vod); string playauth = response.getplayauth(); //播放凭证 log.info("授权码 = {}", playauth); responsedto.setcontent(playauth); //videometa信息 log.info("videometa信息 = {}", response.getvideometa().gettitle()); } catch (exception e) { system.out.print("errormessage = " + e.getlocalizedmessage()); } log.info("获取播放授权结束"); return responsedto; } }
methods: { playurl(url) { let _this = this; console.log("开始播放:", url); // 如果已经有播放器了 就将播放器删除 if (_this.aliplayer) { _this.aliplayer = null; $("#" + _this.playerid + '-player').remove(); } // 初始化播放器 $("#" + _this.playerid).append("<div class=\"prism-player\" id=\"" + _this.playerid + "-player\"></div>"); _this.aliplayer = new aliplayer({ id: _this.playerid + '-player', width: '100%', autoplay: true, //支持播放地址播放,此播放优先级最高 source: url, cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png' }, function (player) { console.log("播放器创建好了") }) }, playvod(vod) { let _this = this; loading.show(); _this.$ajax.get(process.env.vue_app_server + '/file/admin/get-auth/' + vod).then((response) => { loading.hide(); let resp = response.data; if (resp.success) { //如果已经有播放器了,则将播放器div删除 if (_this.aliplayer) { _this.aliplayer = null; $("#" + _this.playerid + '-player').remove(); } // 初始化播放器 $("#" + _this.playerid).append("<div class=\"prism-player\" id=\"" + _this.playerid + "-player\"></div>"); _this.aliplayer = new aliplayer({ id: _this.playerid + '-player', width: '100%', autoplay: false, vid: vod, playauth: resp.content, cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png', encrypttype: 1, //当播放私有加密流时需要设置。 }, function (player) { console.log('播放器创建好了。') }); } else { toast.warning('播放错误。') } }); } },
上述的前端代码只是一个例子,playvod
调用的是阿里的播放器。
到此这篇关于springboot+阿里云oss实现在线视频播放的示例的文章就介绍到这了,更多相关springboot阿里云oss在线视频内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: PHP+Ajax微信手机端九宫格抽奖实例
下一篇: Java学习入门介绍