問題描述
創(chuàng)新互聯(lián)專注于松滋企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,成都做商城網(wǎng)站。松滋網(wǎng)站建設(shè)公司,為松滋等地區(qū)提供建站服務(wù)。全流程按需策劃,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
Spring Boot API 定義 GET 請(qǐng)求 API , 返回視頻流。前端通過
解決方法
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()); } } }
相關(guān)資料
How do I return a video with Spring MVC so that it can be navigated using the html5 tag?
https://stackoverflow.com/questions/3303029/http-range-header
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。