电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

瀏覽:78日期:2023-04-05 17:52:26

阿里云 OSS 是一種云存儲技術(shù),你可以理解為云盤,我們的目標(biāo)是將視頻存儲到云端,然后在前端讀取并播放視頻。

OSS

首先登陸首頁,創(chuàng)建一個存儲桶:https://oss.console.aliyun.com

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

然后找到讀寫權(quán)限:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

將讀寫權(quán)限設(shè)置為公共讀即可:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

在 RAM 中新建一個用戶:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

為其添加權(quán)限,選擇 OSS 的權(quán)限:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

然后點進(jìn)去這個用戶,找到 AccessKey:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

創(chuàng)建之后記下來 secret ,因為他只出現(xiàn)一次,如果沒記住也沒事,可以重新創(chuàng)建新的 key。

下面開始編寫服務(wù)端代碼:

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; // 創(chuàng)建OSSClient實例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ObjectMetadata meta = new ObjectMetadata(); // 指定上傳的內(nèi)容類型。 meta.setContentType('text/plain'); // 通過AppendObjectRequest設(shè)置多個參數(shù)。 AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucket, path, new ByteArrayInputStream(shard.getBytes()), meta); appendObjectRequest.setPosition((long) ((shardIndex - 1) * shardSize)); AppendObjectResult appendObjectResult = ossClient.appendObject(appendObjectRequest); // 文件的64位CRC值。此值根據(jù)ECMA-182標(biāo)準(zhǔn)計算得出。 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; // 創(chuàng)建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; }}

這部分內(nèi)容可以參考阿里云的幫助手冊:https://help.aliyun.com/document_detail/32011.html?spm=a2c4g.11174283.6.915.443b7da2mfhbKq

上面寫的是兩個接口:

追加上傳:/oss-append 簡單上傳:/oss-simple

注意這里的參數(shù)都已經(jīng)在 yml 文件中定義了:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

上面的 KeyId 和 KeySecret 就是之前在創(chuàng)建用戶時給的那兩個,填上就行了。

在前端我們就可以發(fā)送請求獲取數(shù)據(jù),注意這里的對象是我自定義的,大家可以根據(jù)項目需求自行設(shè)置。

_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)是集音視頻上傳、自動化轉(zhuǎn)碼處理、媒體資源管理、分發(fā)加速于一體的全鏈路音視頻點播服務(wù)。

我們同樣需要一個 VOD 的用戶,給它賦予 VOD 的權(quán)限:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

SDK 的使用可以參考文檔:https://help.aliyun.com/document_detail/61063.html?spm=a2c4g.11186623.6.921.418f192bTDCIJN

我們可以在轉(zhuǎn)碼組設(shè)置自己的模板,然后通過 ID 在代碼中使用:

SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例

上傳視頻比較簡單,和 OSS 很像,但是播放視頻要多一個條件,在獲取播放鏈接之前要先取得權(quán)限認(rèn)證,所以下面單獨寫了一個 /get-auth/{vod} 接口,其中的參數(shù)就是 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的本地視頻文件的完整路徑,需要包含文件擴(kuò)展名 String vod = ''; String fileUrl = ''; try { // 初始化VOD客戶端并獲取上傳地址和憑證 DefaultAcsClient vodClient = VodUtil.initVodClient(accessKeyId, accessKeySecret); CreateUploadVideoResponse createUploadVideoResponse = VodUtil.createUploadVideo(vodClient, path); // 執(zhí)行成功會返回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); // 上傳文件,注意是同步上傳會阻塞等待,耗時與文件大小和網(wǎng)絡(luò)上行帶寬有關(guān) 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('獲取播放授權(quán)開始'); 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('授權(quán)碼 = {}', playAuth); responseDto.setContent(playAuth); //VideoMeta信息 LOG.info('VideoMeta信息 = {}', response.getVideoMeta().getTitle()); } catch (Exception e) { System.out.print('ErrorMessage = ' + e.getLocalizedMessage()); } LOG.info('獲取播放授權(quán)結(jié)束'); return responseDto; }}

methods: { playUrl(url) { let _this = this; console.log('開始播放:', url); // 如果已經(jīng)有播放器了 就將播放器刪除 if (_this.aliPlayer) { _this.aliPlayer = null; $('#' + _this.playerId + ’-player’).remove(); } // 初始化播放器 $('#' + _this.playerId).append('<div id='' + _this.playerId + '-player'></div>'); _this.aliPlayer = new Aliplayer({ id: _this.playerId + ’-player’, width: ’100%’, autoplay: true, //支持播放地址播放,此播放優(yōu)先級最高 source: url, cover: ’http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png’ }, function (player) { console.log('播放器創(chuàng)建好了') }) }, 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) { //如果已經(jīng)有播放器了,則將播放器div刪除 if (_this.aliPlayer) { _this.aliPlayer = null; $('#' + _this.playerId + ’-player’).remove(); } // 初始化播放器 $('#' + _this.playerId).append('<div 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, //當(dāng)播放私有加密流時需要設(shè)置。 }, function (player) { console.log(’播放器創(chuàng)建好了。’) }); } else { Toast.warning(’播放錯誤。’) } }); }},

上述的前端代碼只是一個例子,playVod 調(diào)用的是阿里的播放器。

到此這篇關(guān)于SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例的文章就介紹到這了,更多相關(guān)SpringBoot阿里云OSS在線視頻內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 北京银联移动POS机办理_收银POS机_智能pos机_刷卡机_收银系统_个人POS机-谷骐科技【官网】 | 假肢-假肢价格-假肢厂家-河南假肢-郑州市力康假肢矫形器有限公司 | 校园气象站_超声波气象站_农业气象站_雨量监测站_风途科技 | 磁力抛光机_磁力研磨机_磁力去毛刺机_精密五金零件抛光设备厂家-冠古科技 | 穿线管|波纹穿线管|包塑金属软管|蛇皮管?闵彬专注弱电工程? | 皮带式输送机械|链板式输送机|不锈钢输送机|网带输送机械设备——青岛鸿儒机械有限公司 | 水冷散热器_水冷电子散热器_大功率散热器_水冷板散热器厂家-河源市恒光辉散热器有限公司 | 煤机配件厂家_刮板机配件_链轮轴组_河南双志机械设备有限公司 | 自清洗过滤器,浅层砂过滤器,叠片过滤器厂家-新乡市宇清净化 | 建筑资质代办-建筑企业资质代办机构-建筑资质代办公司 | 济南品牌包装设计公司_济南VI标志设计公司_山东锐尚文化传播 | 胀套-锁紧盘-风电锁紧盘-蛇形联轴器「厂家」-瑞安市宝德隆机械配件有限公司 | 搅拌磨|搅拌球磨机|循环磨|循环球磨机-无锡市少宏粉体科技有限公司 | 塑胶跑道_学校塑胶跑道_塑胶球场_运动场材料厂家_中国塑胶跑道十大生产厂家_混合型塑胶跑道_透气型塑胶跑道-广东绿晨体育设施有限公司 | 压力变送器-上海武锐自动化设备有限公司 | 无锡网站建设-做网站-建网站-网页设计制作-阿凡达建站公司 | 食药成分检测_调料配方还原_洗涤剂化学成分分析_饲料_百检信息科技有限公司 | 重庆波纹管|重庆钢带管|重庆塑钢管|重庆联进管道有限公司 | 邢台人才网_邢台招聘网_邢台123招聘【智达人才网】 | 氧化锆陶瓷_氧化锆陶瓷加工_氧化锆陶瓷生产厂家-康柏工业陶瓷有限公司 | 不锈钢水管-不锈钢燃气管-卫生级不锈钢管件-不锈钢食品级水管-广东双兴新材料集团有限公司 | 清洁设备_洗地机/扫地机厂家_全自动洗地机_橙犀清洁设备官网 | 货车视频监控,油管家,货车油管家-淄博世纪锐行电子科技 | 一体化净水器_一体化净水设备_一体化水处理设备-江苏旭浩鑫环保科技有限公司 | 巩义市科瑞仪器有限公司| 蔡司三坐标-影像测量机-3D扫描仪-蔡司显微镜-扫描电镜-工业CT-ZEISS授权代理商三本工业测量 | 福建省教师资格证-福建教师资格证考试网 | 冷水机,风冷冷水机,水冷冷水机,螺杆冷水机专业制造商-上海祝松机械有限公司 | 长沙广告公司|长沙广告制作设计|长沙led灯箱招牌制作找望城湖南锦蓝广告装饰工程有限公司 | 电池挤压试验机-自行车喷淋-车辆碾压试验装置-深圳德迈盛测控设备有限公司 | 炭黑吸油计_测试仪,单颗粒子硬度仪_ASTM标准炭黑自销-上海贺纳斯仪器仪表有限公司(HITEC中国办事处) | 阁楼货架_阁楼平台_仓库仓储设备_重型货架_广州金铁牛货架厂 | 皮带式输送机械|链板式输送机|不锈钢输送机|网带输送机械设备——青岛鸿儒机械有限公司 | 爱佩恒温恒湿测试箱|高低温实验箱|高低温冲击试验箱|冷热冲击试验箱-您身边的模拟环境试验设备技术专家-合作热线:400-6727-800-广东爱佩试验设备有限公司 | 次氯酸钠厂家,涉水级次氯酸钠,三氯化铁生产厂家-淄博吉灿化工 | 智能电表|预付费ic卡水电表|nb智能无线远传载波电表-福建百悦信息科技有限公司 | 艾乐贝拉细胞研究中心 | 国家组织工程种子细胞库华南分库 | 定量包装秤,吨袋包装称,伸缩溜管,全自动包装秤,码垛机器人,无锡市邦尧机械工程有限公司 | PCB设计,PCB抄板,电路板打样,PCBA加工-深圳市宏力捷电子有限公司 | 硬齿面减速机_厂家-山东安吉富传动设备股份有限公司 | 工业机械三维动画制作 环保设备原理三维演示动画 自动化装配产线三维动画制作公司-南京燃动数字 聚合氯化铝_喷雾聚氯化铝_聚合氯化铝铁厂家_郑州亿升化工有限公司 |