问题描述
创新互联专注于松滋企业网站建设,成都响应式网站建设公司,成都做商城网站。松滋网站建设公司,为松滋等地区提供建站服务。全流程按需策划,专业设计,全程项目跟踪,创新互联专业和态度为您提供的服务
Spring Boot API 定义 GET 请求 API , 返回视频流。前端通过 <video> 标签加载并播放视频,效果是必须等整个视频资源全部加载到浏览器才能播放,而且 <video> 标签默认的进度条无法控制视频的播放。最终希望的效果是视频流边加载边播放,且播放器的控制正常使用。
解决方法
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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
网站栏目:SpringBoot静态视频实时播放的实现代码
路径分享:https://www.cdcxhl.com/article20/gscgjo.html
成都网站建设公司_创新互联,为您提供面包屑导航、、标签优化、网站收录、小程序开发、Google
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联