Flask接口签名sign原理与实例代码浅析
354
2022-12-17
SpringBoot静态视频实时播放的实现代码
问题描述
Spring Boot API 定义 GET 请求 API , 返回视频流。前端通过
解决方法
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;
/**
* 预览视频文件, 支持 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());
}
}
}
相关资料
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
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~