1、主要是通过ResourceHttpRequestHandler类来实现,ResourceHttpRequestHandler本身支持分片加载,前端在请求头中携带Range: bytes = 0-5001,就可以从后台自动截取对应大小视频内容。
第一步,先自定义实现一个ResourceHttpRequestHandler
。代码如下:
package com.tec666.moviebar.config;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;/*** @author longge93*/
@Component
public class NonStaticResourceHttpRequestHandler extends ResourceHttpRequestHandler {public final static String ATTR_FILE = "NON-STATIC-FILE";@Overrideprotected Resource getResource(HttpServletRequest request) {String filePath = (String) request.getAttribute(ATTR_FILE);return new FileSystemResource(filePath);}
}
第二步,在视频播放controller中,把本地文件路径传入ResourceHttpRequestHandler
。代码如下:
@Controller
@RequestMapping(value = "/api/baseResource")
public class BaseSourceApiController {@Autowiredprivate NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;private final Logger logger = LoggerFactory.getLogger(this.getClass());@RequestMapping(value = "/video", method = RequestMethod.GET)public void video(HttpServletRequest request,HttpServletResponse response) {try {String path = "D:/abc.mp4";File file = new File(path);if (file.exists()) {request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, path);nonStaticResourceHttpRequestHandler.handleRequest(request, response);} else {response.setStatus(HttpServletResponse.SC_NOT_FOUND);response.setCharacterEncoding(StandardCharsets.UTF_8.toString());}} catch (Exception e) {}}
}