如何使用Spring MVC返回视频,以便可以使用html5<video>标签进行导航?方法 1,响应实体:方法 2、流复制:方法 3,文件系统资源:
如果我在 Web 服务器 (Tomcat) 中有一个文件并创建了一个标记,我可以观看视频、暂停视频、浏览视频,并在视频完成后重新启动视频。
但是,如果我创建一个REST接口,在请求时发送视频文件,并将其URL添加到标签中,我只能播放和暂停。没有倒带,没有快进,没有导航,什么都没有。
那么,有没有办法解决这个问题呢?我是否在某处遗漏了什么?
视频文件与 REST 接口位于同一服务器中,REST 接口仅在确定应发送哪个会话后发送会话并发送视频。
这些是我到目前为止尝试过的方法。它们都有效,但没有一个允许导航。
方法 1,响应实体:
/*
* This will actually load the whole video file in a byte array in memory,
* so it's not recommended.
*/
@RequestMapping(value = "/{id}/preview", method = RequestMethod.GET)
@ResponseBody public ResponseEntity<byte[]> getPreview1(@PathVariable("id") String id, HttpServletResponse response) {
ResponseEntity<byte[]> result = null;
try {
String path = repositoryService.findVideoLocationById(id);
Path path = Paths.get(pathString);
byte[] image = Files.readAllBytes(path);
response.setStatus(HttpStatus.OK.value());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(image.length);
result = new ResponseEntity<byte[]>(image, headers, HttpStatus.OK);
} catch (java.nio.file.NoSuchFileException e) {
response.setStatus(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
return result;
}
方法 2、流复制:
/*
* IOUtils is available in Apache commons io
*/
@RequestMapping(value = "/{id}/preview2", method = RequestMethod.GET)
@ResponseBody public void getPreview2(@PathVariable("id") String id, HttpServletResponse response) {
try {
String path = repositoryService.findVideoLocationById(id);
File file = new File(path)
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader("Content-Disposition", "attachment; filename="+file.getName().replace(" ", "_"));
InputStream iStream = new FileInputStream(file);
IOUtils.copy(iStream, response.getOutputStream());
response.flushBuffer();
} catch (java.nio.file.NoSuchFileException e) {
response.setStatus(HttpStatus.NOT_FOUND.value());
} catch (Exception e) {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
}
}
方法 3,文件系统资源:
@RequestMapping(value = "/{id}/preview3", method = RequestMethod.GET)
@ResponseBody public FileSystemResource getPreview3(@PathVariable("id") String id, HttpServletResponse response) {
String path = repositoryService.findVideoLocationById(id);
return new FileSystemResource(path);
}