SpringMVC流式傳輸媒體數(shù)據(jù)的方法
借助Spring的ResourceHttpRequestHandler可以實(shí)現(xiàn)媒體數(shù)據(jù)的傳輸,比如在線播放視頻、預(yù)覽圖片等。
目前已知Spring Boot傳輸視頻流的方法
- 讀取整個(gè)視頻文件,然后把文件流寫入HttpServletResponse的OutputStream。
(此方法可行,但是需要消耗較多的服務(wù)器資源,且客戶端需要下載整個(gè)視頻才能播放) - 使用HTTP的Range實(shí)現(xiàn)分片加載,但是需要手動(dòng)實(shí)現(xiàn),比較麻煩。
- 使用Spring自帶的ResourceHttpRequestHandler是最佳實(shí)踐。
思路
ResourceHttpRequestHandler是Spring Boot用于加載靜態(tài)資源的一個(gè)類,默認(rèn)用于從"classpath:/static"等目錄讀取靜態(tài)資源,以便前端訪問。我們可以繼承它自定義一個(gè)實(shí)現(xiàn)。
使用方法
在項(xiàng)目的config包(推薦)繼承ResourceHttpRequestHandler并重寫getResource方法,使其返回所需要呈現(xiàn)給前端的資源(org.springframework.core.io.Resource)
package com.example.server.config;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.List;
@Component
public class CustomResourceHttpRequestHandler extends ResourceHttpRequestHandler {
private Resource resource;
@Override
protected Resource getResource(@NonNull HttpServletRequest request) {
return this.resource;
}
public void setResource(Path filePath) throws MalformedURLException {
this.resource = new UrlResource(filePath.toUri());
setLocations(List.of(this.resource));
}
}控制層注入CustomResourceHttpRequestHandler,并向setResource方法傳入文件路徑(java.nio.file.Path),設(shè)置請(qǐng)求頭,最后讓customResourceHttpRequestHandler處理請(qǐng)求。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.file.Path;
import java.nio.file.Paths;
@Controller
@RequestMapping("/files")
public class FileController {
@Autowired
private CustomResourceHttpRequestHandler resourceHttpRequestHandler;
@GetMapping("/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) {
try {
// 解析文件路徑
Path filePath = Paths.get("D:/StorageService").resolve(filename).normalize();
// 檢查文件是否存在
if (!filePath.toFile().exists()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
// 設(shè)置資源路徑
resourceHttpRequestHandler.setResource(filePath);
// 設(shè)置響應(yīng)頭,inline 會(huì)在瀏覽器中顯示或播放文件
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
// 讓 CustomResourceHttpRequestHandler 處理請(qǐng)求
resourceHttpRequestHandler.handleRequest(request, response);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}注意點(diǎn)
控制層返回值需要ResponseEntity類型(org.springframework.http.ResponseEntity),且try-catch不能省略,否則可能會(huì)不斷拋出異常(AsyncRequestNotUsableException和IOException)但不影響正常使用。
其他方案
如果有條件也可以使用MinIO,或者視頻云點(diǎn)播VOD。他們提供了現(xiàn)成的解決方案,通過調(diào)用API可以獲取視頻等文件的直鏈。
參考資料
springboot+vue播放視頻流(無需下載視頻,可以拖動(dòng)進(jìn)度、倍速播放)
到此這篇關(guān)于java的文章就介紹到這了,更多相關(guān)java內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java利用SpEL表達(dá)式實(shí)現(xiàn)權(quán)限校驗(yàn)
這篇文章主要為大家詳細(xì)介紹了Java如何利用SpEL表達(dá)式實(shí)現(xiàn)權(quán)限校驗(yàn)功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01
SpringBoot集成FastDFS實(shí)現(xiàn)防盜鏈功能
FastDFS是一個(gè)高性能的分布式?件系統(tǒng),本文將為大家詳細(xì)介紹一下SpringBoot如何集成FastDFS實(shí)現(xiàn)防盜鏈功能,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
java中字符進(jìn)行全角半角轉(zhuǎn)換示例代碼
全角:指一個(gè)字符占用兩個(gè)標(biāo)準(zhǔn)字符位置,而半角:指一字符占用一個(gè)標(biāo)準(zhǔn)的字符位置,在日常開發(fā)中經(jīng)常會(huì)遇到全角半角轉(zhuǎn)換的要求,下面這篇文章主要給大家介紹了關(guān)于java中字符進(jìn)行全角半角轉(zhuǎn)換的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-08-08
一文詳解如何使用Spring MVC實(shí)現(xiàn)RESTful API接口
本文主要介紹了如何使用SpringMVC實(shí)現(xiàn)RESTful API,包括RESTful的核心概念、設(shè)計(jì)原則、傳參方式比較、SpringMVC實(shí)現(xiàn)示例及關(guān)鍵注解說明,還介紹了API測(cè)試工具和SpringMVC的匹配機(jī)制,強(qiáng)調(diào)了在實(shí)際開發(fā)中保持RESTful風(fēng)格的一致性和合理設(shè)計(jì)資源路徑的重要性2025-10-10
Java實(shí)現(xiàn)SHA-256加密算法的完全解析
SHA-256是一種散列(哈希)算法,用于將任意長度的數(shù)據(jù)映射為固定長度的散列值,以保證數(shù)據(jù)完整性。本文將為大家介紹一下SHA-256加密算法的原理與實(shí)現(xiàn),希望對(duì)大家有所幫助2023-02-02

