当客户端访问类似于此的 URL 时,我正在尝试在我的服务器中下载视频文件:
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(); // <-- an API used in my service. this simply returns an object.
byte[] videoObjectData = SerializationUtils.serialize(object2);
// Get content type by filename.
String contentType = null;
if (contentType == null) {
contentType = "application/octet-stream";
}
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(videoObjectData.length));
response.setHeader("Content-Disposition", "attachment; filename=\"" + "test.flv" + "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(new ByteArrayInputStream(videoObjectData), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 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 教程,但在我的情况下,我没有文件对象作为输入流,只有字节数组对象。
帮助..