我现在是可以根据一个视频的地址拿到对应的数据转成流输出给前端展示。但是如何多个视频一起传过去呢,代码是这样。
1,返回视频流的
package com.example.demo.utils;
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);
}
}
2,controller
package com.example.demo.controller;
import com.example.demo.mapper.VideoUploadMapper;
import com.example.demo.utils.NonStaticResourceHttpRequestHandler;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/SelectVideo")
@AllArgsConstructor
public class SelectVideoController {
private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
@Resource
VideoUploadMapper videoUploadMapper;
@CrossOrigin(origins = "*", maxAge = 3600)
@GetMapping("/policemen")
public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
//视频的地址
String realPath = "D:/video/videoUpload/beae15e0ae3345eb8ce3f54636b295c9.mp4";
Path filePath = Paths.get(realPath );
//Files.exists:用来测试路径文件是否存在
if (Files.exists(filePath)) {
//获取视频的类型
String mimeType = Files.probeContentType(filePath);
if (StringUtils.hasText(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());
}
}
}
前端的代码video
<video
src="http://localhost:8001/SelectVideo/policemen"
controls="controls"
width="100%"
id="myvideo"
>
</video>