当前位置: 首页>编程语言>正文

springboot视频转二进制流存储到后端 springboot视频上传


SpringBoot实现阿里云视频上传删除

  • 创建SpringBoot工程引入阿里云依赖
  • 创建一个工具类
  • controller
  • 测试小案例
  • 视频播放


创建SpringBoot工程引入阿里云依赖

在配置文件中写

# 最大上传单个文件大小:默认1M
spring.servlet.multipart.max-file-size=1024MB
# 最大置总上传的数据大小 :默认10M
spring.servlet.multipart.max-request-size=1024MB
<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
        <version>4.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-vod</artifactId>
              <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-sdk-vod-upload</artifactId>
            <version>1.4.11</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
             <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.2</version>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
        </dependency>

注意

springboot视频转二进制流存储到后端 springboot视频上传,springboot视频转二进制流存储到后端 springboot视频上传_spring boot,第1张

这个jar包maven仓库是没有的,要手动打包进自己的maven仓库,

springboot视频转二进制流存储到后端 springboot视频上传,springboot视频转二进制流存储到后端 springboot视频上传_上传_02,第2张

百度网盘拿:

链接:https://pan.baidu.com/s/1brmvs_lYKGDsc84G8ecsog

提取码:1111

–来自百度网盘超级会员V2的分享

Cmd进入窗口
执行命令安装jar包
mvn install:install-file “-DgroupId=com.aliyun” “-DartifactId=aliyun-sdk-vod-upload” “-Dversion=1.4.11” “-Dpackaging=jar” “-Dfile=aliyun-java-vod-upload-1.4.11.jar”

创建一个工具类

public class AliyunVodSDKUtils {
    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;
    }
}

controller

/**
* @description: TODO
* @author MIS
* @date 2022/8/9 11:03
* @version 1.0
*/
@Api(description="视频管理")
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VideoAdminController {

    @ApiOperation(value = "视频上传")
    @PostMapping("uploadVideo")
    public R uploadVideo(MultipartFile file){
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
       //截取字符串
            String title=originalFilename.substring(0,originalFilename.lastIndexOf("."));
            UploadStreamRequest request = new UploadStreamRequest(
                   "写自己阿里云的AccessKey ID",
                    "写自己阿里云的AccessKey Secret"
                    title,
                    originalFilename,
                    inputStream
            );
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            /* 如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因 */
            String videoId = response.getVideoId();
            return R.ok().data("videoId",videoId);
        }catch (IOException e){
            e.printStackTrace();
            throw new GuliException(20001,"视频上传异常");
        }
    }

    @ApiOperation(value = "批量删除视频")
    @DeleteMapping("delVideoList")
    public R delVideo(@RequestParam("videoIdList") List<String> videoIdList){
        try {
            //*初始化客户端对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient("写自己阿里云的AccessKey ID",
                    "写自己阿里云的AccessKey Secret");
            //*创建请求对象(不同操作,类不同)
            DeleteVideoRequest request = new DeleteVideoRequest();

            //*向请求中设置参数
            //支持传入多个视频ID,多个用逗号分隔
            //11,12,13
            String videoIds = org.apache.commons.lang.StringUtils.join(videoIdList.toArray(),",");
            request.setVideoIds(videoIds);
            //*调用客户端对象方法发送请求,拿到响应
            client.getAcsResponse(request);
            return R.ok();

        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"批量删除视频失败");
        }

    }

    @ApiOperation(value = "删除视频")
    @DeleteMapping("delVideo/{videoId}")
    public R delVideo(@PathVariable("videoId") String videoId){

        try {
            //*初始化客户端对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient("写自己阿里云的AccessKey ID",
                    "写自己阿里云的AccessKey Secret");
            //*创建请求对象(不同操作,类不同)
            DeleteVideoRequest request = new DeleteVideoRequest();
            //*创建响应对象(不同操作,类不同)
            //DeleteVideoResponse response = new DeleteVideoResponse();
            //*向请求中设置参数
            //支持传入多个视频ID,多个用逗号分隔
            request.setVideoIds(videoId);
            //*调用客户端对象方法发送请求,拿到响应
            client.getAcsResponse(request);
            return R.ok();

        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"删除视频失败");
        }

    }
}

测试小案例

springboot视频转二进制流存储到后端 springboot视频上传,springboot视频转二进制流存储到后端 springboot视频上传_上传_03,第3张

里面的ID即为下面

request.setVideoId(“6ac5c76f257640fa8870d300346b7e9c”);的参数

/**
* @description: TODO
* @author MIS
* @date 2022/8/9 6:42
* @version 1.0
*/

public class Teste {

    String accessKeyId = "写自己阿里云的AccessKey ID";
    String accessKeySecret = "写自己阿里云的AccessKey Secret";
   //拿到地址,但盗链
    @Test
    public void testGetPlayInfo() throws ClientException {
        //*初始化客户端对象
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(accessKeyId, accessKeySecret);
//*创建请求对象(不同操作,类不同)
        GetPlayInfoRequest request = new GetPlayInfoRequest();
//*创建响应对象(不同操作,类不同)
        GetPlayInfoResponse response = new GetPlayInfoResponse();
//*向请求中设置参数
        request.setVideoId("6ac5c76f257640fa8870d300346b7e9c");
// *调用客户端对象方法发送请求,拿到响应
        response = client.getAcsResponse(request);
//*从响应中拿到数据
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        //播放地址
        for (GetPlayInfoResponse.PlayInfo playInfo : playInfoList) {
            System.out.print("PlayInfo.PlayURL = " + playInfo.getPlayURL() + "\n");
        }
    }

    @Test
    public void testGetVideoPlayAuth()throws ClientException{
        //*初始化客户端对象
        DefaultAcsClient client = AliyunVodSDKUtils.initVodClient(accessKeyId, accessKeySecret);
        //*创建请求对象(不同操作,类不同)
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        //*创建响应对象(不同操作,类不同)
        GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
        //*向请求中设置参数
        request.setVideoId("6ac5c76f257640fa8870d300346b7e9c");
        // *调用客户端对象方法发送请求,拿到响应
        response = client.getAcsResponse(request);
        //*从响应中拿到数据
        String playAuth = response.getPlayAuth();
        System.out.println("playAuth = "+playAuth);
    }

    @Test
    public void testUploadVideo(){

        //1.音视频上传-本地文件上传
        //视频标题(必选)
        String title = "阿里云OVD服务阿里云视频点播";
        //本地文件上传和文件流上传时,文件名称为上传文件绝对路径,如:/User/sample/文件名称.mp4 (必选)
        //文件名必须包含扩展名
        String fileName = "E:\a\test.mp4";
        //本地文件上传
        UploadVideoRequest request = new UploadVideoRequest(accessKeyId, accessKeySecret, title, fileName);
        /* 可指定分片上传时每个分片的大小,默认为1M字节 */
        request.setPartSize(1 * 1024 * 1024L);
        /* 可指定分片上传时的并发线程数,默认为1,(注:该配置会占用服务器CPU资源,需根据服务器情况指定)*/
        request.setTaskNum(1);
/* 是否开启断点续传, 默认断点续传功能关闭。当网络不稳定或者程序崩溃时,再次发起相同上传请求,可以继续未完成的上传任务,适用于超时3000秒仍不能上传完成的大文件。
    注意: 断点续传开启后,会在上传过程中将上传位置写入本地磁盘文件,影响文件上传速度,请您根据实际情况选择是否开启*/
        request.setEnableCheckpoint(false);

        UploadVideoImpl uploader = new UploadVideoImpl();
        UploadVideoResponse response = uploader.uploadVideo(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n");  //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            /* 如果设置回调URL无效,不影响视频上传,可以返回VideoId同时会返回错误码。其他情况上传失败时,VideoId为空,此时需要根据返回错误码分析具体错误原因 */
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }

    }
}

视频播放

1.继上面conreoller,根据上传视频的ID,获取视频播放凭证

@ApiOperation(value = "根据视频id获取视频播放凭证")
    @GetMapping("getPlayAuth/{vid}")
    public R getPlayAuth(@PathVariable String vid){
        try {
            //*初始化客户端对象
            DefaultAcsClient client = AliyunVodSDKUtils.initVodClient("写自己阿里云的AccessKey ID",
                    "写自己阿里云的AccessKey Secret");
            //(2)创建request、response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            GetVideoPlayAuthResponse response = new GetVideoPlayAuthResponse();
            //(3)向request设置视频id
            request.setVideoId(vid);
            //播放凭证有过期时间,默认值:100秒 。取值范围:100~3000。
            //request.setAuthInfoTimeout(200L);
            //(4)调用初始化方法实现功能
            response = client.getAcsResponse(request);
            //(5)调用方法返回response对象,获取内容
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        } catch (ClientException e) {
            throw new GuliException(20001,"获取视频凭证失败");
        }
    }

2.获取到视频播放凭证后,前端展示

body>
    <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"></script>
    <div class="prism-player" id="J_prismPlayer"></div>
    <script>
        var player = new Aliplayer({
            id: 'J_prismPlayer',
            width: '100%',
            autoplay: false,
            //视频播放封面地址
            cover: 'http://liveroom-img.oss-cn-qingdao.aliyuncs.com/logo.png',
            //播放配置
            vid: '',
            //这里playauth,放入视频播放凭证即可
            playauth: '这里playauth,放入视频播放凭证即可',
        }, function (player) {
            console.log('播放器创建好了。')
        });
    </script>

</body>

3.前端展示,根据视频地址播放

<body>
<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"></script>
<div  class="prism-player" id="J_prismPlayer"></div>
<script>
    var player = new Aliplayer({
        id: 'J_prismPlayer',
        width: '100%',
         //是否自动播放
        autoplay: false,
         //视频播放封面地址
        cover: 'http://outin-840fba6d170211edacc700163e1a65b6.oss-cn-shanghai.aliyuncs.com/cb4963c827b8457b865c0e04e7508ee5/snapshots/376da4151b804647adaa9469fe1a272f-00001.jpg?Expires=1660557869&OSSAccessKeyId=LTAI3DkxtsbUyNYV&Signature=MX8UiybsZ16%2B%2FZ%2BNUz8cwdVs59o%3D',
        //视频播放地址
        source : 'https://outin-840fba6d170211edacc700163e1a65b6.oss-cn-shanghai.aliyuncs.com/sv/29410f29-182a0c0a11f/29410f29-182a0c0a11f.mp4?Expires=1660558034&OSSAccessKeyId=LTAI3DkxtsbUyNYV&Signature=jCC%2FJPqvUPghNH1NYhIgeF605L4%3D',
    },function(player){
        console.log('播放器创建好了。')
    });
</script>

</body>



https://www.xamrdz.com/lan/5qe1935562.html

相关文章: