项目要求从文件服务器读取音视频文件,以流的方式传给前台,并能够播放视频。
做了一个demo,用html5的video,audio标签实现。
后台实现代码:
@GetMapping(value = "/getVideos")
public String getVideos(HttpServletRequest request, HttpServletResponse response)
{try {FileInputStream fis = null;OutputStream os = null ;fis = new FileInputStream("C:\\Users\\zhangxin\\Desktop\\douyin.mp4");int size = fis.available(); // 得到文件大小byte data[] = new byte[size];fis.read(data); // 读数据fis.close();fis = null;response.setContentType("video/mp4"); // 设置返回的文件类型os = response.getOutputStream();os.write(data);os.flush();os.close();os = null;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;
}
前端实现代码:
<video width="1120" height="540" controls="controls" id="video" preload="auto" ><source src="getVideos" type="video/mp4">
</video>
src写getVideos可以直接跳转到后台找到这个方法。
最后实现效果: