使用Java servlet的video下载/流

当客户端访问URL类似于此时,我试图在我的服务器中下载video文件:

http://localhost:8088/openmrs/moduleServlet/patientnarratives/videoDownloadServlet?videoObsId=61 

我试过这段代码。 但它不起作用。 当我访问servlet时,它只下载一个空白(0大小)文件。

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Integer videoObsId = Integer.parseInt(request.getParameter("videoObsId")); Obs complexObs = Context.getObsService().getComplexObs(videoObsId, OpenmrsConstants.RAW_VIEW); ComplexData complexData = complexObs.getComplexData(); Object object2 = complexData.getData(); //  0) { output.write(buffer, 0, length); } } finally { // Gently close streams. close(output); close(input); } } // Add error handling above and remove this try/catch catch (Exception e) { log.error("unable to get file", e); } } private static void close(Closeable resource) { if (resource != null) { try { resource.close(); } catch (IOException e) { // Do your thing with the exception. Print it, log it or mail it. e.printStackTrace(); } } } 

我使用过BalusC的fileservlet教程,但在我的情况下,我没有文件对象作为输入流只是字节数组对象。

救命..

您找到的servlet确实不能用于流式传输video文件。 它更像是一个简单的文件下载servlet,用于静态文件,如PDF,XLS等。

许多video播放器要求服务器支持所谓的HTTP范围请求。 即它必须能够通过具有Range标头的请求返回video文件的特定字节范围。 例如,在10000字节长的文件上只有索引1000到2000的字节。 这是必需的,以便能够足够快地跳过特定范围的video流而无需下载整个文件和/或通过创建多个HTTP连接来提高缓冲速度,每个HTTP连接请求video文件的不同部分。

然而,这是servlet中的许多附加代码,需要很好地理解HTTP Range规范。 您找到的文件servlet的同一作者在此扩展文件servlet的风格中提供了一个随时可用的示例。 在您的特定情况下,可能建议首先将文件保存到基于本地磁盘文件系统的缓存(例如,通过File#createTempFile()和HTTP会话中的某些键),这样您就不需要再次从外部服务获取它然后再次。