最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2020年11月29日 11:40:09   作者:碩子鴿  
這篇文章主要介紹了SpringBoot+阿里云OSS實現(xiàn)在線視頻播放的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

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

OSS

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


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


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


在 RAM 中新建一個用戶:


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


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


創(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 文件中定義了:

上面的 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)限:


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

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


上傳視頻比較簡單,和 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的本地視頻文件的完整路徑,需要包含文件擴展名
    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 class=\"prism-player\" 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 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, //當(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Springboot中yml對于list列表配置方式詳解

    Springboot中yml對于list列表配置方式詳解

    這篇文章主要介紹了Springboot中yml對于list列表配置方式詳解,使用@ConfigurationProperties讀取yml配置文件過程中會遇到讀取yml文件中列表,Config里面使用List集合接收,方法比較簡單,需要的朋友可以參考下
    2023-11-11
  • 如何在java中正確使用注釋

    如何在java中正確使用注釋

    在編寫程序時,經(jīng)常需要添加一些注釋,用以描述某段代碼的作用。 一般來說,對于一份規(guī)范的程序源代碼而言,注釋應(yīng)該占到源代碼的 1/3 以上。下面我們來詳細(xì)了解一下吧
    2019-06-06
  • SpringBoot集成Spring Security用JWT令牌實現(xiàn)登錄和鑒權(quán)的方法

    SpringBoot集成Spring Security用JWT令牌實現(xiàn)登錄和鑒權(quán)的方法

    這篇文章主要介紹了SpringBoot集成Spring Security用JWT令牌實現(xiàn)登錄和鑒權(quán)的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • 基于openeuler的DataGear部署文檔

    基于openeuler的DataGear部署文檔

    本文詳細(xì)介紹了如何在openEuler操作系統(tǒng)上安裝和配置JDK以及DataGear,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2025-03-03
  • 淺談Spring與SpringMVC父子容器的關(guān)系與初始化

    淺談Spring與SpringMVC父子容器的關(guān)系與初始化

    這篇文章主要介紹了淺談Spring與SpringMVC父子容器的關(guān)系與初始化,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Java由淺入深通關(guān)抽象類與接口上

    Java由淺入深通關(guān)抽象類與接口上

    在類中沒有包含足夠的信息來描繪一個具體的對象,這樣的類稱為抽象類,接口是Java中最重要的概念之一,它可以被理解為一種特殊的類,不同的是接口的成員沒有執(zhí)行體,是由全局常量和公共的抽象方法所組成,本文給大家介紹Java抽象類和接口,感興趣的朋友一起看看吧
    2022-04-04
  • java控制臺實現(xiàn)可視化日歷小程序

    java控制臺實現(xiàn)可視化日歷小程序

    這篇文章主要為大家詳細(xì)介紹了java控制臺實現(xiàn)可視化日歷小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-12-12
  • MyBatis攔截器的實現(xiàn)原理

    MyBatis攔截器的實現(xiàn)原理

    這篇文章主要介紹了MyBatis攔截器的實現(xiàn)原理,Mybatis攔截器并不是每個對象里面的方法都可以被攔截的,其具體內(nèi)容感興趣的小伙伴課題參考一下下面文章內(nèi)容
    2022-08-08
  • MybatisPlus中QueryWrapper常用方法總結(jié)

    MybatisPlus中QueryWrapper常用方法總結(jié)

    MyBatis-Plus是一個Mybatis增強版工具,在MyBatis上擴充了其他功能沒有改變其基本功能,為了簡化開發(fā)提交效率而存在,queryWrapper是mybatis plus中實現(xiàn)查詢的對象封裝操作類,本文就給大家總結(jié)了MybatisPlus中QueryWrapper的常用方法,需要的朋友可以參考下
    2023-07-07
  • Java 和 Scala 如何調(diào)用變參

    Java 和 Scala 如何調(diào)用變參

    這篇文章主要介紹了Java 和 Scala 如何調(diào)用變參,幫助大家更好的理解和學(xué)習(xí)Java與Scala,感興趣的朋友可以了解下
    2020-09-09

最新評論

兴宁市| 洞头县| 夹江县| 平山县| 兰州市| 许昌县| 房山区| 莱州市| 鸡西市| 保德县| 西华县| 万荣县| 镇宁| 丹东市| 扎兰屯市| 大安市| 延寿县| 东城区| 资阳市| 池州市| 辉南县| 上杭县| 麦盖提县| 广昌县| 苗栗市| 洪洞县| 甘肃省| 赤峰市| 勐海县| 长垣县| 繁峙县| 无棣县| 邓州市| 上饶县| 大连市| 湘潭市| 临夏县| 法库县| 诸暨市| 元江| 穆棱市|