ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

boot实现视频播放

2021-07-07 10:33:06  阅读:131  来源: 互联网

标签:视频 filePath request boot import 播放 response


SpringBoot+vue的项目中,实现前端播放视频

SpringBoot 定义GET请求ApI,返回视频流,前端通过

话不多说,走起


一、新建如下类,用于返回视频流

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文件夹的绝对地址
//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测试

到了这一步基本可以通过访问后端url进行视频播放了
测试:http://localhost:8080/file/video

不出意外的话是可以播放的,如果播放不了的,再检查下视频所在的物理地址

第三步没问题的话进行第四步


四、前端播放

前端播放代码

<video controls autoplay src="http://localhost:8080/file/video"/>

这里有个要注意的点:建议 src属性 直接放在<video>里,别放在<video>标签下的<source>里,会播放不了的
over
————————————————
版权声明:本文为CSDN博主「sJLei_38759449」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38759449/article/details/104496464

标签:视频,filePath,request,boot,import,播放,response
来源: https://www.cnblogs.com/niudaxianren/p/14980378.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有