SpringMVC 字节流实现播放多媒体

来源:互联网 发布:用友软件凭证打印 编辑:程序博客网 时间:2024/05/16 11:56

1、前言

在项目中,我们会遇到在线预览,播放MP3、图片、MP4等。用户上传文件后,将路径存储在数据库中,我们可动态读取数据库的数据,然后通过返回文件路径的字符串,在src中发送请求。当然这需要带参数。后台返回流。


2、前台代码:

<script type="text/javascript">function getVideo(id){window.location.href="${pageContext.request.contextPath }/Test/getVideo.do?id="+id;}</script></head><body><h3>${message }</h3><h1>Hello !!!</h1><button id="btn" onclick="getVideo('ea48576f30be1669971699c09ad05c94');">播放</button><%-- <video id="video" ><source src="${path }"></video> --%><audio id="mp3" src="${path }" autoplay="true" controls="true"></audio></body>

3、后台代码:

@Controller@RequestMapping("/Test")public class TestController {/** * 视频跳转 * @param id * @return */@RequestMapping("/getVideo.do")public ModelAndView getVideo(String id) {ModelAndView mav = new ModelAndView("success");mav.addObject("path", "/Test/Test/video.do?id="+id);return mav;}/** * 视频流读取 * @param id * @param response * @throws Exception */@RequestMapping("/video.do")public @ResponseBody void video(String id, HttpServletResponse response)throws Exception{File file = new File("E:/1.mp3");FileInputStream in = new FileInputStream(file);ServletOutputStream out = response.getOutputStream();byte[] b = null;while(in.available() >0) {if(in.available()>10240) {b = new byte[10240];}else {b = new byte[in.available()];}in.read(b, 0, b.length);out.write(b, 0, b.length);}in.close();out.flush();out.close();}}

Reference:

[1] 陶国荣, HTML5实战, 机械工业出版社, 2012, 116-117


原创粉丝点击