跳坑日志
SpringBoot+vue的項(xiàng)目中,實(shí)現(xiàn)前端播放視頻
SpringBoot 定義GET請(qǐng)求ApI,返回視頻流,前端通過(guò)
話不多說(shuō),走起
一、新建如下類,用于返回視頻流
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
@RequestMapping("/file")
@AllArgsConstructor
public class FileRestController {
private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;
@GetMapping("/video")
public void videoPreview(HttpServletRequest request, HttpServletResponse response) throws Exception {
//假如我把視頻1.mp4放在了static下的video文件夾里面
//sourcePath 是獲取resources文件夾的絕對(duì)地址
//realPath 即是視頻所在的磁盤地址
String sourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
String realPath = sourcePath +"static/video/1.mp4";
Path filePath = Paths.get(realPath );
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());
}
}
}
三、后端url測(cè)試
到了這一步基本可以通過(guò)訪問(wèn)后端url進(jìn)行視頻播放了
測(cè)試:http://localhost:8080/file/video
不出意外的話是可以播放的,如果播放不了的,再檢查下視頻所在的物理地址
第三步?jīng)]問(wèn)題的話進(jìn)行第四步
四、前端播放
前端播放代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-407055.html
<video controls autoplay src="http://localhost:8080/file/video"/>
這里有個(gè)要注意的點(diǎn):建議 src屬性 直接放在里,別放在標(biāo)簽下的里,會(huì)播放不了的文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-407055.html
over
到了這里,關(guān)于(前后端分離)SpringBoot+Vue實(shí)現(xiàn)視頻播放的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!