問題描述
Spring Boot API 定義 GET 請(qǐng)求 API 褪迟, 返回視頻流美浦。前端通過 <video> 標(biāo)簽加載并播放視頻,效果是必須等整個(gè)視頻資源全部加載到瀏覽器才能播放戚哎,而且 <video> 標(biāo)簽?zāi)J(rèn)的進(jìn)度條無法控制視頻的播放裸诽。最終希望的效果是視頻流邊加載邊播放,且播放器的控制正常使用型凳。
解決方法
Spring Framework 文件請(qǐng)求處理
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;
/**
* 預(yù)覽視頻文件, 支持 byte-range 請(qǐng)求
*/
@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());
}
}
}