最近在做一个大屏系统时,需要在界面中播放一段视频,由于跨域问题,最后决定使用视频流的方式,把音频文件传到前端进行播放。
后端Java代码如下:
@RequestMapping(value = "/videoFlow", method = RequestMethod.GET)
public void videoFlow(HttpServletRequest request,
HttpServletResponse httpServletResponse, String fileName) {
String templeId = request.getParameter("templeId");// 寺庙ID
String propName[] = new String[] { "fileSubordinateId", "fileFrom" };
Object propValue[] = new Object[] { Long.parseLong(templeId), 1 };
List<TempleFile> tfList = templeFileService.queryByProerties(propName,
propValue);
String fileSrc = null;
if (StringUtils.isNotBlank(tfList)) {
for (TempleFile tf : tfList) {
if (tf.getFileType().intValue() == 2) {
fileSrc = tf.getFileSavePath();
break;
}
}
}
byte[] bytes = changeTobyte(fileSrc);
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse.setContentLength(bytes.length);
try {
httpServletResponse.getOutputStream().write(bytes);
} catch (IOException e) {
System.out.println("IO异常----");
}
}
public byte[] changeTobyte(String filePath) {
byte[] buffer = null;
try {
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
前端代码
如下所示:
<video width="375" height="150" controls> <source src="http://XXX.XXX.XXX.XX/sms/bigscree/videoFlow?templeId=1" type="video/mp4"></video>
结果上面两步,就可以在前端正常播放map4文件了。