本文介绍如何通过H5页面通过数据流的方式播放服务端的视频文件,可以兼容PC、Android和IOS环境。
H5页面可以通过 标签来播放视频。一般的方式如下:
your browser does not support the video tag
src中指定了要播放的视频的URL,为具体的视频文件路径。当将访问请求变为getVideo.do?fileId=xxx 这种形式,服务端返回字节流的时候后端实现需要一些更改。
一般的方式是读本地文件然后写到response中,代码实现如下:
public void downFile(File downloadFile,
HttpServletResponse response,
HttpServletRequest request) throws Exception {
response.reset();
response.setContentType("video/mp4;charset=UTF-8");
InputStream in = null;
ServletOutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(downloadFile);
if(in !=null){
byte[] b = new byte[1024];
int i = 0;
while((i = in.read(b)) > 0){
out.write(b, 0, i);
}
out.flush();
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(in != null) {
try { in.close(); } catch (IOException e) { }
in = null;
}
if(out != null) {
try { out.close(); } catch (IOException e) { }
out = null;
}
}
}
这种方式在PC端和Android手机上都能正常显示,但在IOS手机上通过Safari浏览器就不能播放。ios目前获取视频的时候请求头会带一个与断点续传有关的信息。对于ios来说,他不是一次性请求全部文件的,一般首先