其他
Spring Boot 应用 - 静态视频资源实时播放新姿势
问题描述
Spring Boot API 定义 GET 请求 API , 返回视频流。前端通过 video 标签加载并播放视频,效果是必须等整个视频资源全部加载到浏览器才能播放,而且 video 标签默认的进度条无法控制视频的播放。最终希望的效果是视频流边加载边播放,且播放器的控制正常使用。
解决方法
Spring Framework 文件请求处理
1import org.springframework.core.io.FileSystemResource;
2import org.springframework.core.io.Resource;
3import org.springframework.stereotype.Component;
4import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
5
6import javax.servlet.http.HttpServletRequest;
7import java.nio.file.Path;
8
9
10public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {
11
12 public final static String ATTR_FILE = "NON-STATIC-FILE";
13
14
15 protected Resource getResource(HttpServletRequest request) {
16 final Path filePath = (Path) request.getAttribute(ATTR_FILE);
17 return new FileSystemResource(filePath);
18 }
19
20}
Controller 层
1@RestController
2@AllArgsConstructor
3public class FileRestController {
4
5 private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
6
7 /**
8 * 预览视频文件, 支持 byte-range 请求
9 */
10 @GetMapping("/video")
11 public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
12 String path = request.getParameter("path");
13 Path filePath = Paths.get(path);
14 if (Files.exists(filePath)) {
15 String mimeType = Files.probeContentType(filePath);
16 if (!StringUtils.isEmpty(mimeType)) {
17 response.setContentType(mimeType);
18 }
19 request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, filePath);
20 nonStaticResourceHttpRequestHandler.handleRequest(request, response);
21 } else {
22 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
23 response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
24 }
25 }
26
27}
相关资料
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
● 深入浅出 CAS
如有收获,请帮忙转发,您的鼓励是作者最大的动力,谢谢!