Java-SpringBoot-Range请求头设置实现视频分段传输

打印 上一主题 下一主题

主题 933|帖子 933|积分 2799

老实说,人太懒了,现在基本都不喜欢写笔记了,但是网上有关Range请求头的文章都太水了
下面是抄的一段StackOverflow的代码...自己大修改过的,写的注释挺全的,应该直接看得懂,就不解释了
写的不好...只是希望能给视频网站开发的新手一点点帮助吧.
业务场景:视频分段传输、视频多段传输(理论上配合前端能实现视频预览功能, 没有尝试过)
下面是API测试图

  • 请求头设置

  • 返回结果

  • 响应头结果

  • 这是我写给前端同学的文档,凑活看看吧...摆烂了


  • 若浏览器存在完整的缓存, 或者叛逆期到了,不存在缓存也想用缓存
    设置请求头:If-None-Match   ETAG(前端无缓存请求后端下载时,后端返回的请求头中的)/*(叛逆期到了,用这个也可以直接304)
    如果不存在缓存:直接不设置该请求头
  • 如果想把一次Range请求分成多次进行,那么就要设置该请求头(可以不设置,不设置直接过验证, 设置的话比较规范)
    设置请求头:If-Match        ETAG(若错误的ETAG,返回412,SC_PRECONDITION_FAILED)
  • 设置Range请求头:
    比如文件总大小100
    标准格式:bytes=-20/20 表示后20个字节;bytes=20-100/80 表示20-100总计80个字节
    bytes=20-40/20,60-80/20 表示一个Range请求返回两个文件块,这也是Range请求存在的意义
    若Range请求不规范,则返回416,SC_REQUESTED_RANGE_NOT_SATISFIABLE
  • If-Range请求头,可以不设置;If-Range 头字段通常用于断点续传的下载过程中,用来自从上次中断后,确保下载的资源没有发生改变。
    If-Range        ETAG 如果ETAG不相等,那么直接返回全部的文件即 bytes:0-size(不进行分段)
  • 设置Accept请求头,不设置或者不为video/mp4则默认attachment
    inline是断点传输需要的,而attachment就是出现另存为对话框(文件下载)
  • 我返回了一堆响应头,具体什么用的到时候再说,需要注意的就是ETAG是缓存的身份标识,Expires是缓存的过期时间
  1. package org.demo.util;
  2. import jakarta.servlet.ServletOutputStream;
  3. import jakarta.servlet.http.HttpServletRequest;
  4. import jakarta.servlet.http.HttpServletResponse;
  5. import lombok.RequiredArgsConstructor;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.demo.constant.EntityConstant;
  8. import org.demo.mapper.VideoMapper;
  9. import org.demo.pojo.Video;
  10. import org.demo.service.MinioService;
  11. import org.springframework.context.annotation.Scope;
  12. import org.springframework.stereotype.Component;
  13. import java.io.BufferedInputStream;
  14. import java.io.IOException;
  15. import java.io.InputStream;
  16. import java.io.OutputStream;
  17. import java.util.ArrayList;
  18. import java.util.Arrays;
  19. import java.util.List;
  20. /**
  21. * Created by kevin on 10/02/15.
  22. * See full code here : https://github.com/davinkevin/Podcast-Server/blob/d927d9b8cb9ea1268af74316cd20b7192ca92da7/src/main/java/lan/dk/podcastserver/utils/multipart/MultipartFileSender.java
  23. * Updated by limecoder on 23/04/19
  24. */
  25. @Slf4j
  26. @Component(value = "multipartFileSender")
  27. @RequiredArgsConstructor
  28. @Scope("prototype")
  29. public class MultipartFileSender {
  30.     private static final int DEFAULT_BUFFER_SIZE = 20480; // ..bytes = 20KB.
  31.     private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week.
  32.     private static final String MULTIPART_BOUNDARY = "MULTIPART_BYTERANGES";
  33.     private static final String PATTERN = "^bytes=\\d*-\\d*(/\\d*)?(,\\d*-\\d*(/\\d*)?)*$";
  34.     private final HttpServletRequest request;
  35.     private final HttpServletResponse response;
  36.     private final VideoMapper videoMapper;
  37.     private final MinioService minioService;
  38.     public void sent(Long videoId) throws Exception {
  39.         if (response == null || request == null) {
  40.             log.warn("http-request/http-response 注入失败");
  41.             return;
  42.         }
  43.         Video video = videoMapper.selectById(videoId);
  44.         /*
  45.         * 处理视频不存在的情况
  46.         * */
  47.         if (video == null) {
  48.             log.error("videoId doesn't exist at database : {}", videoId);
  49.             response.sendError(HttpServletResponse.SC_NOT_FOUND);
  50.             return;
  51.         }
  52.         Long size = video.getSize();
  53.         String md5 = video.getMd5();
  54.         // 处理缓存信息 ---------------------------------------------------
  55.         /*
  56.         * If-None-Match是缓存请求头,如果缓存的值与文件的md5相同或者值为*,那么就直接提示前端直接使用缓存即可
  57.         * 并将md5再次返回给前端
  58.         * */
  59.         // If-None-Match header should contain "*" or ETag. If so, then return 304.
  60.         String ifNoneMatch = request.getHeader("If-None-Match");
  61.         if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, md5)) {
  62.             response.setHeader("ETag", md5); // Required in 304.
  63.             response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
  64.             return;
  65.         }
  66.         // 确保Range请求合法 ----------------------------------------------------
  67.         /*
  68.         * 对于 GET 和 HEAD 方法,搭配 Range首部使用,可以用来保证新请求的范围与之前请求的范围是对同一份资源的请求。
  69.         * 如果 ETag 无法匹配,那么需要返回 416 (Range Not Satisfiable,范围请求无法满足) 响应。
  70.         * */
  71.         // If-Match header should contain "*" or ETag. If not, then return 412.
  72.         String ifMatch = request.getHeader("If-Match");
  73.         if (ifMatch != null && !HttpUtils.matches(ifMatch, md5)) {
  74.             response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
  75.             return;
  76.         }
  77.         // 验证和解析Range请求头 -------------------------------------------------------------
  78.         // Prepare some variables. The full Range represents the complete file.
  79.         Range full = new Range(0, size - 1, size);
  80.         List<Range> ranges = new ArrayList<>();
  81.         // Validate and process Range and If-Range headers.
  82.         String range = request.getHeader("Range");
  83.         if (range != null) {
  84.             /*
  85.             * 如果Range请求头不满足规范格式,那么发送错误请求
  86.             * */
  87.             // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
  88.             if (!range.matches(PATTERN)) {
  89.                 response.setHeader("Content-Range", "bytes */" + size); // Required in 416.
  90.                 response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
  91.                 return;
  92.             }
  93.             /*
  94.             * If-Range 头字段通常用于断点续传的下载过程中,用来自从上次中断后,确保下载的资源没有发生改变。
  95.             * */
  96.             String ifRange = request.getHeader("If-Range");
  97.             if (ifRange != null && !ifRange.equals(md5)) {
  98.                 // 如果资源发生了改变,直接将数据全部返回
  99.                 ranges.add(full);
  100.             }
  101.             /*
  102.             * 如果If-Range请求头是合法的,也就是视频数据并没有更新
  103.             * 例子:bytes:10-80,bytes:80-180
  104.             * */
  105.             // If any valid If-Range header, then process each part of byte range.
  106.             if (ranges.isEmpty()) {
  107.                 // substring去除bytes:
  108.                 for (String part : range.substring(6).split(",")) {
  109.                     // Assuming a file with size of 100, the following examples returns bytes at:
  110.                     // 50-80 (50 to 80), 40- (40 to size=100), -20 (size-20=80 to size=100).
  111.                     //去除多余空格
  112.                     part = part.trim();
  113.                     /*
  114.                     * 解决20-80及20-80/60的切割问题
  115.                     * */
  116.                     long start = Range.subLong(part, 0, part.indexOf("-"));
  117.                     int index1 = part.indexOf("/");
  118.                     int index2 = part.length();
  119.                     int index = index2 > index1 && index1 > 0 ? index1 : index2;
  120.                     long end = Range.subLong(part, part.indexOf("-") + 1, index);
  121.                     // 如果是-开头的情况 -20
  122.                     if (start == -1) {
  123.                         start = size - end;
  124.                         end = size - 1;
  125.                         // 如果是20但没有-的情况,或者end> size - 1的情况
  126.                     } else if (end == -1 || end > size - 1) {
  127.                         end = size - 1;
  128.                     }
  129.                     /*
  130.                     * 如果范围不合法, 80-10
  131.                     * */
  132.                     // Check if Range is syntactically valid. If not, then return 416.
  133.                     if (start > end) {
  134.                         response.setHeader("Content-Range", "bytes */" + size); // Required in 416.
  135.                         response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
  136.                         return;
  137.                     }
  138.                     // Add range.                    
  139.                     ranges.add(new Range(start, end, size));
  140.                 }
  141.             }
  142.         }
  143.         // Prepare and initialize response --------------------------------------------------------
  144.         // Get content type by file name and set content disposition.
  145.         String disposition = "inline";
  146.         // If content type is unknown, then set the default value.
  147.         // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
  148.         // To add new content types, add new mime-mapping entry in web.xml.
  149.         String contentType = "video/mp4";
  150.         /*
  151.         * 经过测试当accept为"video/mp4"是inline, 其他情况都是attachment
  152.         * */
  153.         // Else, expect for images, determine content disposition. If content type is supported by
  154.         // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
  155.         String accept = request.getHeader("Accept");
  156.         disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
  157.         log.debug("Content-Type : {}", contentType);
  158.         // Initialize response.
  159.         response.reset();
  160.         response.setBufferSize(DEFAULT_BUFFER_SIZE);
  161.         response.setHeader("Content-Type", contentType);
  162.         String videoPath = video.getVideoPath();
  163.         response.setHeader("Content-Disposition", disposition + ";filename="" + videoPath.substring(videoPath.lastIndexOf('/') + 1) + """);
  164.         log.debug("Content-Disposition: {}, fileName: {}", disposition, videoPath.substring(videoPath.lastIndexOf('/') + 1));
  165.         response.setHeader("Accept-Ranges", "bytes");
  166.         response.setHeader("ETag", md5);
  167.         // 设置缓存过期时间
  168.         response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
  169.         // Send requested file (part(s)) to client ------------------------------------------------
  170.         /*
  171.         * 注意minioService okhttp3经过测试最大只能一次传8kb, 而bufferedInputStream的默认缓存区恰好8kb
  172.         * */
  173.         // Prepare streams.
  174.         try (InputStream input = new BufferedInputStream(minioService.getDownloadInputStream(EntityConstant.VIDEO_BUCKET, videoPath));
  175.              ServletOutputStream output = response.getOutputStream()) {
  176.             if (ranges.isEmpty() || ranges.get(0) == full) {
  177.                 // Return full file.
  178.                 log.debug("返回全部的视频文件,不进行划分");
  179.                 response.setContentType(contentType);
  180.                 response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
  181.                 response.setHeader("Content-Length", String.valueOf(full.length));
  182.                 Range.copy(input, output, size, full.start, full.length);
  183.             } else if (ranges.size() == 1) {
  184.                 // Return single part of file.
  185.                 Range r = ranges.get(0);
  186.                 log.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
  187.                 response.setContentType(contentType);
  188.                 response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
  189.                 response.setHeader("Content-Length", String.valueOf(r.length));
  190.                 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.
  191.                 // Copy single part range.
  192.                 Range.copy(input, output, size, r.start, r.length);
  193.             } else {
  194. /*              发送多种数据的多部分对象集合:
  195.                 多部分对象集合包含:
  196.                 1、multipart/form-data
  197.                 在web表单文件上传时使用
  198.                 2、multipart/byteranges
  199.                 状态码206响应报文包含了多个范围的内容时使用。*/
  200.                 // Return multiple parts of file.
  201.                 response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
  202.                 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.
  203.                 // Cast back to ServletOutputStream to get the easy println methods.
  204.                 // Copy multi part range.
  205.                 for (Range r : ranges) {
  206.                     log.debug("Return multi part of file : from ({}) to ({})", r.start, r.end);
  207.                     // Add multipart boundary and header fields for every range.
  208.                     output.println();
  209.                     output.println("--" + MULTIPART_BOUNDARY);
  210.                     output.println("Content-Type: " + contentType);
  211.                     output.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);
  212.                     // Copy single part range of multi part range.
  213.                     Range.copy(input, output, size, r.start, r.length);
  214.                 }
  215.                 // End with multipart boundary.
  216.                 output.println();
  217.                 output.println("--" + MULTIPART_BOUNDARY + "--");
  218.             }
  219.         }
  220.     }
  221.     private static class Range {
  222.         long start;
  223.         long end;
  224.         long length;
  225.         long total;
  226.         /**
  227.          * Construct a byte range.
  228.          * @param start Start of the byte range.
  229.          * @param end End of the byte range.
  230.          * @param total Total length of the byte source.
  231.          */
  232.         public Range(long start, long end, long total) {
  233.             this.start = start;
  234.             this.end = end;
  235.             this.length = end - start + 1;
  236.             this.total = total;
  237.         }
  238.         public static long subLong(String value, int beginIndex, int endIndex) {
  239.             String substring = value.substring(beginIndex, endIndex);
  240.             return (substring.length() > 0) ? Long.parseLong(substring) : -1;
  241.         }
  242.         private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length) throws IOException {
  243.             byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
  244.             int read;
  245.             if (inputSize == length) {
  246.                 // Write full range.
  247.                 while ((read = input.read(buffer)) > 0) {
  248.                     output.write(buffer, 0, read);
  249.                     output.flush();
  250.                 }
  251.             } else {
  252.                 input.skip(start);
  253.                 long toRead = length;
  254.                 while ((read = input.read(buffer)) > 0) {
  255.                     if ((toRead -= read) > 0) {
  256.                         output.write(buffer, 0, read);
  257.                         output.flush();
  258.                     } else {
  259.                         output.write(buffer, 0, (int) toRead + read);
  260.                         output.flush();
  261.                         break;
  262.                     }
  263.                 }
  264.             }
  265.         }
  266.     }
  267.     private static class HttpUtils {
  268.         /**
  269.          * Returns true if the given accept header accepts the given value.
  270.          * @param acceptHeader The accept header.
  271.          * @param toAccept The value to be accepted.
  272.          * @return True if the given accept header accepts the given value.
  273.          */
  274.         public static boolean accepts(String acceptHeader, String toAccept) {
  275.             String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
  276.             Arrays.sort(acceptValues);
  277.             return Arrays.binarySearch(acceptValues, toAccept) > -1
  278.                     || Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
  279.                     || Arrays.binarySearch(acceptValues, "*/*") > -1;
  280.         }
  281.         /**
  282.          * Returns true if the given match header matches the given value.
  283.          * @param matchHeader The match header.
  284.          * @param toMatch The value to be matched.
  285.          * @return True if the given match header matches the given value.
  286.          */
  287.         public static boolean matches(String matchHeader, String toMatch) {
  288.             String[] matchValues = matchHeader.split("\\s*,\\s*");
  289.             Arrays.sort(matchValues);
  290.             return Arrays.binarySearch(matchValues, toMatch) > -1
  291.                     || Arrays.binarySearch(matchValues, "*") > -1;
  292.         }
  293.         
  294.     }
  295. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

王海鱼

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表