java 使用 aws s3 sdk 通过分段下载来实现 html 页面 video 的断点播放、拖动进度播放

参考博客:

  1. Java 视频流分段返回

  2. java 拉取 aws s3 视频流返回给浏览器:

     @Override
     public void playVideo(Long fileLength,String key,HttpServletRequest request,HttpServletResponse response) {
         OutputStream outputStream = null;
         S3ObjectInputStream s3ObjectInputStream = null;
         try {
             outputStream = response.getOutputStream();
    
             // 获取从哪个字节开始读取文件
             String rangeHeader = request.getHeader("Range");
             if (rangeHeader == null) {
                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Required 'Range' header is missing");
                 return;
             }
    
             long startByte = 0;
             long endByte = fileLength - 1;
             if (rangeHeader.startsWith("bytes=")) {
                 String[] rangeParts = rangeHeader.substring(6).split("-");
                 startByte = Long.parseLong(rangeParts[0]);
                 endByte = rangeParts.length > 1 ? startByte : fileLength - 1;
             }
    
             if (startByte > endByte || startByte < 0 || endByte >= fileLength) {
                 response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, "Requested range not satisfiable");
                 return;
             }
    
             // 设置响应头
             response.setHeader("Content-Type", "video/mp4");
             response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
             response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + fileLength);
    
             // 从S3获取视频流
             GetObjectRequest getObjectRequest = new GetObjectRequest(this.fileBucket, key).withRange(startByte, endByte + 1);
             S3Object s3Object = this.amazonS3.getObject(getObjectRequest);
             s3ObjectInputStream = s3Object.getObjectContent();
    
             // 将视频流响应给客户端
             byte[] buffer = new byte[1024 * 1024]; // 使用1MB的缓冲区
             int bytesRead;
             long totalBytesRead = 0;
             while ((bytesRead = s3ObjectInputStream.read(buffer)) != -1 && totalBytesRead <= (endByte - startByte + 1)) {
                 outputStream.write(buffer, 0, bytesRead);
                 totalBytesRead += bytesRead;
             }
             response.setContentLength((int) (endByte - startByte + 1)); // 设置实际返回的数据长度
         } catch (Exception e) {
             // 处理异常
             log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e );
             // 处理异常
             try {
                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
             }catch ( Exception e ){
                 log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e );
             }
         }finally {
             if( outputStream != null ){
                 try {
                     outputStream.close();
                 }catch ( Exception e1 ){
                     log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e1 );
                 }
             }
             if( s3ObjectInputStream != null ){
                 try {
                     s3ObjectInputStream.close();
                 }catch ( Exception e1 ){
                     log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e1 );
                 }
             }
         }
     }
    
  3. java读物本地视频文件返回给浏览器:

java 复制代码
    @Override
    public void playVideo(HttpServletRequest request, HttpServletResponse response) {
        RandomAccessFile randomAccessFile = null;
        OutputStream outputStream = null;
        try {
            response.reset();
            // File file = new File("D:\\素材\\视频\\crazy_max_small.mp4");
            File file = new File("D:\\视频\\888.mp4");
            long fileLength = file.length();
            // 随机读文件
            randomAccessFile = new RandomAccessFile(file, "r");

            //获取从那个字节开始读取文件
            String rangeString = request.getHeader("Range");
            System.out.println(rangeString);
            long range=0;
            if (rangeString!=null) {
                range = Long.valueOf(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
            }
            //获取响应的输出流
            outputStream = response.getOutputStream();
            //设置内容类型
            response.setHeader("Content-Type", "video/mp4");
            //返回码需要为206,代表只处理了部分请求,响应了部分数据
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

            // 移动访问指针到指定位置
            randomAccessFile.seek(range);
            // 每次请求只返回1MB的视频流
            byte[] bytes = new byte[1024 * 1024];
            int len = randomAccessFile.read(bytes);
            //设置此次相应返回的数据长度
            response.setContentLength(len);
            //设置此次相应返回的数据范围
            response.setHeader("Content-Range", "bytes "+range+"-"+(fileLength-1)+"/"+fileLength);
            // 将这1MB的视频流响应给客户端
            outputStream.write(bytes, 0, len);
            System.out.println("返回数据区间:【"+range+"-"+(range+len)+"】");
        }catch ( Exception e ){
            log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e );
            // 处理异常
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");
            }catch ( Exception e1 ){
                log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e1 );
            }
        }finally {
            if( outputStream != null){
                try {
                    outputStream.close();
                }catch ( Exception e){
                    log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e );
                }
            }
            if( randomAccessFile != null ){
                try {
                    randomAccessFile.close();
                }catch ( Exception e ){
                    log.error( CommonConstans.EXCEPTION_LOG_PREFIX,e );
                }
            }
        }
相关推荐
学不会•44 分钟前
css数据不固定情况下,循环加不同背景颜色
前端·javascript·html
Theodore_10222 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸3 小时前
01-spring security认证笔记
java·笔记·spring
世间万物皆对象3 小时前
Spring Boot核心概念:日志管理
java·spring boot·单元测试
没书读了4 小时前
ssm框架-spring-spring声明式事务
java·数据库·spring
小二·4 小时前
java基础面试题笔记(基础篇)
java·笔记·python
开心工作室_kaic4 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
懒洋洋大魔王4 小时前
RocketMQ的使⽤
java·rocketmq·java-rocketmq
武子康4 小时前
Java-06 深入浅出 MyBatis - 一对一模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据仓库·sql·mybatis·springboot·springcloud
转世成为计算机大神5 小时前
易考八股文之Java中的设计模式?
java·开发语言·设计模式