Java-SpringBoot-Range請求頭設置實現視頻分段傳輸

来源:https://www.cnblogs.com/LimeCoder/archive/2023/04/19/17334386.html
-Advertisement-
Play Games

老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下麵是抄的一段StackOverflow的代碼...自己大修改過的,寫的註釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ...


老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了
下麵是抄的一段StackOverflow的代碼...自己大修改過的,寫的註釋挺全的,應該直接看得懂,就不解釋了
寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧.

業務場景:視頻分段傳輸、視頻多段傳輸(理論上配合前端能實現視頻預覽功能, 沒有嘗試過)
下麵是API測試圖

  1. 請求頭設置

  2. 返回結果

  3. 響應頭結果

  4. 這是我寫給前端同學的文檔,湊活看看吧...擺爛了

  • 若存在緩存則設置請求頭:If-None-Match ETAG
    如果不存在緩存:直接不設置該請求頭
  • 如果想把一次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是緩存的過期時間
package org.demo.util;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.demo.constant.EntityConstant;
import org.demo.mapper.VideoMapper;
import org.demo.pojo.Video;
import org.demo.service.MinioService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by kevin on 10/02/15.
 * See full code here : https://github.com/davinkevin/Podcast-Server/blob/d927d9b8cb9ea1268af74316cd20b7192ca92da7/src/main/java/lan/dk/podcastserver/utils/multipart/MultipartFileSender.java
 * Updated by limecoder on 23/04/19
 */
@Slf4j
@Component(value = "multipartFileSender")
@RequiredArgsConstructor
@Scope("prototype")
public class MultipartFileSender {

    private static final int DEFAULT_BUFFER_SIZE = 20480; // ..bytes = 20KB.
    private static final long DEFAULT_EXPIRE_TIME = 604800000L; // ..ms = 1 week.
    private static final String MULTIPART_BOUNDARY = "MULTIPART_BYTERANGES";
    private static final String PATTERN = "^bytes=\\d*-\\d*(/\\d*)?(,\\d*-\\d*(/\\d*)?)*$";

    private final HttpServletRequest request;
    private final HttpServletResponse response;
    private final VideoMapper videoMapper;
    private final MinioService minioService;

    public void sent(Long videoId) throws Exception {
        if (response == null || request == null) {
            log.warn("http-request/http-response 註入失敗");
            return;
        }

        Video video = videoMapper.selectById(videoId);

        /*
        * 處理視頻不存在的情況
        * */
        if (video == null) {
            log.error("videoId doesn't exist at database : {}", videoId);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        Long size = video.getSize();
        String md5 = video.getMd5();

        // 處理緩存信息 ---------------------------------------------------

        /*
        * If-None-Match是緩存請求頭,如果緩存的值與文件的md5相同或者值為*,那麼就直接提示前端直接使用緩存即可
        * 並將md5再次返回給前端
        * */
        // If-None-Match header should contain "*" or ETag. If so, then return 304.
        String ifNoneMatch = request.getHeader("If-None-Match");
        if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, md5)) {
            response.setHeader("ETag", md5); // Required in 304.
            response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }


        // 確保Range請求合法 ----------------------------------------------------

        /*
        * 對於 GET 和 HEAD 方法,搭配 Range首部使用,可以用來保證新請求的範圍與之前請求的範圍是對同一份資源的請求。
        * 如果 ETag 無法匹配,那麼需要返回 416 (Range Not Satisfiable,範圍請求無法滿足) 響應。
        * */
        // If-Match header should contain "*" or ETag. If not, then return 412.
        String ifMatch = request.getHeader("If-Match");
        if (ifMatch != null && !HttpUtils.matches(ifMatch, md5)) {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
            return;
        }

        // 驗證和解析Range請求頭 -------------------------------------------------------------

        // Prepare some variables. The full Range represents the complete file.
        Range full = new Range(0, size - 1, size);
        List<Range> ranges = new ArrayList<>();

        // Validate and process Range and If-Range headers.
        String range = request.getHeader("Range");
        if (range != null) {

            /*
            * 如果Range請求頭不滿足規範格式,那麼發送錯誤請求
            * */
            // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
            if (!range.matches(PATTERN)) {
                response.setHeader("Content-Range", "bytes */" + size); // Required in 416.
                response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                return;
            }

            /*
            * If-Range 頭欄位通常用於斷點續傳的下載過程中,用來自從上次中斷後,確保下載的資源沒有發生改變。
            * */
            String ifRange = request.getHeader("If-Range");
            if (ifRange != null && !ifRange.equals(md5)) {
                // 如果資源發生了改變,直接將數據全部返回
                ranges.add(full);
            }

            /*
            * 如果If-Range請求頭是合法的,也就是視頻數據並沒有更新
            * 例子:bytes:10-80,bytes:80-180
            * */
            // If any valid If-Range header, then process each part of byte range.
            if (ranges.isEmpty()) {
                // substring去除bytes:
                for (String part : range.substring(6).split(",")) {
                    // Assuming a file with size of 100, the following examples returns bytes at:
                    // 50-80 (50 to 80), 40- (40 to size=100), -20 (size-20=80 to size=100).

                    //去除多餘空格
                    part = part.trim();

                    /*
                    * 解決20-80及20-80/60的切割問題
                    * */
                    long start = Range.subLong(part, 0, part.indexOf("-"));
                    int index1 = part.indexOf("/");
                    int index2 = part.length();
                    int index = index2 > index1 && index1 > 0 ? index1 : index2;
                    long end = Range.subLong(part, part.indexOf("-") + 1, index);

                    // 如果是-開頭的情況 -20
                    if (start == -1) {
                        start = size - end;
                        end = size - 1;
                        // 如果是20但沒有-的情況,或者end> size - 1的情況
                    } else if (end == -1 || end > size - 1) {
                        end = size - 1;
                    }

                    /*
                    * 如果範圍不合法, 80-10
                    * */
                    // Check if Range is syntactically valid. If not, then return 416.
                    if (start > end) {
                        response.setHeader("Content-Range", "bytes */" + size); // Required in 416.
                        response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                        return;
                    }

                    // Add range.                    
                    ranges.add(new Range(start, end, size));
                }
            }
        }

        // Prepare and initialize response --------------------------------------------------------

        // Get content type by file name and set content disposition.
        String disposition = "inline";

        // If content type is unknown, then set the default value.
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        // To add new content types, add new mime-mapping entry in web.xml.
        String contentType = "video/mp4";
        /*
        * 經過測試當accept為"video/mp4"是inline, 其他情況都是attachment
        * */
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
        log.debug("Content-Type : {}", contentType);


        // Initialize response.
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setHeader("Content-Type", contentType);
        String videoPath = video.getVideoPath();
        response.setHeader("Content-Disposition", disposition + ";filename=\"" + videoPath.substring(videoPath.lastIndexOf('/') + 1) + "\"");
        log.debug("Content-Disposition: {}, fileName: {}", disposition, videoPath.substring(videoPath.lastIndexOf('/') + 1));
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", md5);
        // 設置緩存過期時間
        response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
        // Send requested file (part(s)) to client ------------------------------------------------

        /*
        * 註意minioService okhttp3經過測試最大隻能一次傳8kb, 而bufferedInputStream的預設緩存區恰好8kb
        * */
        // Prepare streams.
        try (InputStream input = new BufferedInputStream(minioService.getDownloadInputStream(EntityConstant.VIDEO_BUCKET, videoPath));
             ServletOutputStream output = response.getOutputStream()) {

            if (ranges.isEmpty() || ranges.get(0) == full) {

                // Return full file.
                log.debug("返回全部的視頻文件,不進行劃分");
                response.setContentType(contentType);
                response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total);
                response.setHeader("Content-Length", String.valueOf(full.length));
                Range.copy(input, output, size, full.start, full.length);

            } else if (ranges.size() == 1) {

                // Return single part of file.
                Range r = ranges.get(0);
                log.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
                response.setContentType(contentType);
                response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
                response.setHeader("Content-Length", String.valueOf(r.length));
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                // Copy single part range.
                Range.copy(input, output, size, r.start, r.length);

            } else {

/*              發送多種數據的多部分對象集合:
                多部分對象集合包含:
                1、multipart/form-data
                在web表單文件上傳時使用
                2、multipart/byteranges
                狀態碼206響應報文包含了多個範圍的內容時使用。*/
                // Return multiple parts of file.
                response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

                // Cast back to ServletOutputStream to get the easy println methods.

                // Copy multi part range.
                for (Range r : ranges) {
                    log.debug("Return multi part of file : from ({}) to ({})", r.start, r.end);
                    // Add multipart boundary and header fields for every range.
                    output.println();
                    output.println("--" + MULTIPART_BOUNDARY);
                    output.println("Content-Type: " + contentType);
                    output.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    Range.copy(input, output, size, r.start, r.length);
                }

                // End with multipart boundary.
                output.println();
                output.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }

    }

    private static class Range {
        long start;
        long end;
        long length;
        long total;

        /**
         * Construct a byte range.
         * @param start Start of the byte range.
         * @param end End of the byte range.
         * @param total Total length of the byte source.
         */
        public Range(long start, long end, long total) {
            this.start = start;
            this.end = end;
            this.length = end - start + 1;
            this.total = total;
        }

        public static long subLong(String value, int beginIndex, int endIndex) {
            String substring = value.substring(beginIndex, endIndex);
            return (substring.length() > 0) ? Long.parseLong(substring) : -1;
        }

        private static void copy(InputStream input, OutputStream output, long inputSize, long start, long length) throws IOException {
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int read;

            if (inputSize == length) {
                // Write full range.
                while ((read = input.read(buffer)) > 0) {
                    output.write(buffer, 0, read);
                    output.flush();
                }
            } else {
                input.skip(start);
                long toRead = length;

                while ((read = input.read(buffer)) > 0) {
                    if ((toRead -= read) > 0) {
                        output.write(buffer, 0, read);
                        output.flush();
                    } else {
                        output.write(buffer, 0, (int) toRead + read);
                        output.flush();
                        break;
                    }
                }
            }
        }
    }
    private static class HttpUtils {

        /**
         * Returns true if the given accept header accepts the given value.
         * @param acceptHeader The accept header.
         * @param toAccept The value to be accepted.
         * @return True if the given accept header accepts the given value.
         */
        public static boolean accepts(String acceptHeader, String toAccept) {
            String[] acceptValues = acceptHeader.split("\\s*(,|;)\\s*");
            Arrays.sort(acceptValues);

            return Arrays.binarySearch(acceptValues, toAccept) > -1
                    || Arrays.binarySearch(acceptValues, toAccept.replaceAll("/.*$", "/*")) > -1
                    || Arrays.binarySearch(acceptValues, "*/*") > -1;
        }

        /**
         * Returns true if the given match header matches the given value.
         * @param matchHeader The match header.
         * @param toMatch The value to be matched.
         * @return True if the given match header matches the given value.
         */
        public static boolean matches(String matchHeader, String toMatch) {
            String[] matchValues = matchHeader.split("\\s*,\\s*");
            Arrays.sort(matchValues);
            return Arrays.binarySearch(matchValues, toMatch) > -1
                    || Arrays.binarySearch(matchValues, "*") > -1;
        }
        
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 作為一個技術架構師,不僅僅要緊跟行業技術趨勢,還要結合研發團隊現狀及痛點,探索新的交付方案。在日常中,你是否遇到如下問題 “ 業務需求排期長研發是瓶頸;非研發角色感受不到研發技改提效的變化;引入ISV 團隊又擔心質量和安全,培訓周期長“等等,基於此我們探索了一種新的技術體系及交付方案來解決如上問題。 ...
  • 值傳遞不會改變本身,引用傳遞(如果傳遞的值需要實例化到堆里)如果發生修改了會改變本身。 1.基本數據類型都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ...
  • 第一個 Scala 程式 shell裡面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 文件形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ...
  • 理解 函數指針 指向函數的指針。比如: 理解函數指針的偽代碼 void (*p)(int type, char *data); // 定義一個函數指針p void func(int type, char *data); // 聲明一個函數func p = func; // 將指針p指向函數func ...
  • 本文首發於公眾號:Hunter後端 原文鏈接:Django筆記二十五之資料庫函數之日期函數 日期函數主要介紹兩個大類,Extract() 和 Trunc() Extract() 函數作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等數據 Trunc() 的作用則是截取,比如 2022-0 ...
  • 什麼是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的電腦上模擬模擬各種電腦功能來實現的。由一套位元組碼指令集、一組寄存器、一個棧、一個垃圾回收堆和一個存儲方法域等組成。JVM屏蔽了與操作系統平臺相關的信息,使得Java程式只需要生成在Java虛擬機 ...
  • 更新完微信服務號的模板消息之後,我又趕緊把微信小程式的訂閱消息給實現了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 消息推送平臺🔥推送下發【郵件】【簡訊】【微信服務號】【微信小程式】【企業微信】【釘釘】等消息類型。 https://gitee.com/zhongfuch ...
  • 緩衝流 緩衝流, 也叫高效流, 按照數據類型分類: 位元組緩衝流:BufferedInputStream,BufferedOutputStream 字元緩衝流:BufferedReader,BufferedWriter 緩衝流的基本原理,是在創建流對象時,會創建一個內置的預設大小的緩衝區數組,通過緩衝 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...