(前后端分离)SpringBoot+Vue实现视频播放
跳坑日志
SpringBoot+vue的项目中,实现前端播放视频
SpringBoot 定义GET请求ApI,返回视频流,前端通过
话不多说,走起
一、新建如下类,用于返回视频流
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";@Overrideprotected Resource getResource(HttpServletRequest request) {final Path filePath = (Path) request.getAttribute(ATTR_FILE);return new FileSystemResource(filePath);}}
二、再写Controller层
这里主要的是得到视频所在的物理地址
@RestController
@RequestMapping("/file")
@AllArgsConstructor
public class FileRestController {private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;@GetMapping("/video")public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {//假如我把视频1.mp4放在了static下的video文件夹里面//sourcePath 是获取resources文件夹的绝对地址//realPath 即是视频所在的磁盘地址String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);String realPath = sourcePath +"static/video/1.mp4";Path filePath = Paths.get(realPath );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());}}}
三、后端url测试
到了这一步基本可以通过访问后端url进行视频播放了
测试:http://localhost:8080/file/video
不出意外的话是可以播放的,如果播放不了的,再检查下视频所在的物理地址
第三步没问题的话进行第四步
四、前端播放
前端播放代码
这里有个要注意的点:建议 src属性 直接放在
over
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
