如果使用流来播放视频,那原理无非是先读取服务器上的视频文件放入内存中,然后客户端读取,但是在最初次的使用中出现了内存泄露和效率特别低的问题(这段代码已经不见了所以不贴出来),后来翻阅了无数帖子,修正了一下代码,在读取和写出文件的地方做了个优化使他分段读取
@GetMapping("/details")
public Return getVideos(CourseWare courseWare,HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
//获取地址视频
CourseWare courseWareByIdAndCode = courseWareService.findCourseWareByIdAndCode(courseWare);
FileInputStream fis = null;
OutputStream os = null;
//因为是本地服务器所以截取部分来让路径变成相对路径
fis = new FileInputStream(courseWareByIdAndCode.getVido().substring(20));
//截取后缀,获取文件类型
String vidoSuffix = courseWareByIdAndCode.getVido().substring(courseWareByIdAndCode.getVido().lastIndexOf(".") + 1);
response.setContentType("video/"+vidoSuffix); // 设置返回的文件类型
os = response.getOutputStream();
int size = fis.available(); // 得到文件大小
System.out.println(size);
//在这里采用多次分段刷新解决内存泄露
for (int i = 0; i < 80; i++) {
byte data[] = new byte[size/80];
fis.read(data); // 读数据
os.write(data);//写数据
os.flush();
}
fis.close();
//方便GC回收,释放内存
fis = null;
os.close();
//方便GC回收,释放内存
os = null;
return new Return().yes("");
} catch (FileNotFoundException e) {
e.printStackTrace()