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 );
                }
            }
        }
相关推荐
Yaml433 分钟前
Spring Boot 与 Vue 共筑二手书籍交易卓越平台
java·spring boot·后端·mysql·spring·vue·二手书籍
小小小妮子~34 分钟前
Spring Boot详解:从入门到精通
java·spring boot·后端
hong16168836 分钟前
Spring Boot中实现多数据源连接和切换的方案
java·spring boot·后端
aloha_7891 小时前
从零记录搭建一个干净的mybatis环境
java·笔记·spring·spring cloud·maven·mybatis·springboot
记录成长java2 小时前
ServletContext,Cookie,HttpSession的使用
java·开发语言·servlet
睡觉谁叫~~~2 小时前
一文解秘Rust如何与Java互操作
java·开发语言·后端·rust
程序媛小果2 小时前
基于java+SpringBoot+Vue的旅游管理系统设计与实现
java·vue.js·spring boot
小屁孩大帅-杨一凡3 小时前
java后端请求想接收多个对象入参的数据
java·开发语言
java1234_小锋3 小时前
使用 RabbitMQ 有什么好处?
java·开发语言
TangKenny3 小时前
计算网络信号
java·算法·华为