SpringBoot靜態(tài)視頻實時播放的實現(xiàn)代碼
問題描述
Spring Boot API 定義 GET 請求 API , 返回視頻流。前端通過 <video> 標(biāo)簽加載并播放視頻,效果是必須等整個視頻資源全部加載到瀏覽器才能播放,而且 <video> 標(biāo)簽?zāi)J(rèn)的進度條無法控制視頻的播放。最終希望的效果是視頻流邊加載邊播放,且播放器的控制正常使用。
解決方法
Spring Framework 文件請求處理
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; import javax.servlet.http.HttpServletRequest; import java.nio.file.Path; @Component public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler { public final static String ATTR_FILE = "NON-STATIC-FILE"; @Override protected Resource getResource(HttpServletRequest request) { final Path filePath = (Path) request.getAttribute(ATTR_FILE); return new FileSystemResource(filePath); } }
Controller 層
@RestController @AllArgsConstructor public class FileRestController { private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler; /** * 預(yù)覽視頻文件, 支持 byte-range 請求 */ @GetMapping("/video") public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = request.getParameter("path"); Path filePath = Paths.get(path); if (Files.exists(filePath)) { String mimeType = Files.probeContentType(filePath); if (!StringUtils.isEmpty(mimeType)) { response.setContentType(mimeType); } request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath); nonStaticResourceHttpRequestHandler.handleRequest(request, response); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); } } }
相關(guān)資料
How do I return a video with Spring MVC so that it can be navigated using the html5 tag?
https://stackoverflow.com/questions/3303029/http-range-header
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java圖形界面之JFrame,JLabel,JButton詳解
這篇文章主要介紹了Java圖形界面之JFrame、JLabel、JButton詳解,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04java實現(xiàn)微信公眾平臺發(fā)送模板消息的示例代碼
這篇文章主要介紹了java實現(xiàn)微信公眾平臺發(fā)送模板消息的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09springboot中使用jpa下hibernate的ddl-auto方式
這篇文章主要介紹了springboot中使用jpa下hibernate的ddl-auto方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02mybatis條件語句中帶數(shù)組參數(shù)的處理
這篇文章主要介紹了mybatis條件語句中帶數(shù)組參數(shù)的處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09springboot整合websocket實現(xiàn)群聊思路代碼詳解
通過springboot引入websocket,實現(xiàn)群聊,通過在線websocket測試進行展示。本文重點給大家介紹springboot整合websocket實現(xiàn)群聊功能,代碼超級簡單,感興趣的朋友跟隨小編一起學(xué)習(xí)吧2021-05-05