SpringBoot靜態(tài)視頻實(shí)時(shí)播放的實(shí)現(xiàn)代碼
問題描述
Spring Boot API 定義 GET 請求 API , 返回視頻流。前端通過 <video> 標(biāo)簽加載并播放視頻,效果是必須等整個(gè)視頻資源全部加載到瀏覽器才能播放,而且 <video> 標(biāo)簽?zāi)J(rèn)的進(jì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)文章
Spring Security注冊過濾器注意事項(xiàng)詳解
前兩天和小伙伴聊了 Spring Security+JWT 實(shí)現(xiàn)無狀態(tài)登錄,然后有小伙伴反饋了一個(gè)問題,感覺這是一個(gè)我們平時(shí)寫代碼容易忽略的問題,所以本文給大家介紹了Spring Security注冊過濾器注意事項(xiàng),需要的朋友可以參考下2024-06-06
一文總結(jié) Shiro 實(shí)戰(zhàn)教程
shiro是apache的一個(gè)開源框架,是一個(gè)權(quán)限管理的框架,實(shí)現(xiàn) 用戶認(rèn)證、用戶授權(quán),這篇文章詳細(xì)總結(jié)了shiro用法,感興趣的同學(xué)可以參考閱讀2023-04-04
Java多線程中的ThreadLocal應(yīng)用場景及問題解讀
這篇文章主要介紹了Java多線程中的ThreadLocal應(yīng)用場景及問題解讀,ThreadLocal這個(gè)類在多線程并發(fā)中主要的使用場景是什么呢,我們都知道多線程并發(fā)問題實(shí)際就是多個(gè)線程對公共資源訪問和修改問題,需要的朋友可以參考下2023-12-12

