【发布时间】:2015-01-08 14:41:51
【问题描述】:
我有一个 Spring 应用程序,它使用带有 WebMVC 的 JPA 存储库,我正在尝试扩展它以支持图像。我可以上传图像并将它们存储在服务器端,但是在使用客户端实际检索图像时,我实际上无法成功发送响应。
首先,这是我公开的客户端 API:
@Streaming
@GET(PATIENT_EXTRA_PATH + "/{id}" + GET_IMAGE_RELPATH)
public Response getImageData(@Path(ID) long id, @Query(IMAGE_FILE) String imageFile);
这是我第一次尝试实现:
@RequestMapping(value = PainManagementSvcApi.PATIENT_EXTRA_PATH + "/{id}" +
PainManagementSvcApi.GET_IMAGE_RELPATH, method = RequestMethod.GET,
produces = MediaType.IMAGE_JPEG_VALUE)
public HttpServletResponse getImageData(@PathVariable(PainManagementSvcApi.ID) long id,
@RequestParam(PainManagementSvcApi.IMAGE_FILE) String imageFile,
Principal principal, HttpServletResponse response) {
// Do some stuff to ensure image availability and access
// All of this works
response.setContentType("image/jpeg");
imageFileManager.copyImageData(imageFile, response.getOutputStream());
response.setStatus(HttpServletResponse.SC_OK);
// Return the response
return response;
}
但是,这种方法在测试时会产生以下异常:
javax.servlet.ServletException:无法解析名称为“dispatcherServlet”的 servlet 中名称为“extra/1/image”的视图
看了一会,我想我可能需要@ResponseBody注解以及如下:
@RequestMapping(value = PainManagementSvcApi.PATIENT_EXTRA_PATH + "/{id}" +
PainManagementSvcApi.GET_IMAGE_RELPATH, method = RequestMethod.GET,
produces = MediaType.IMAGE_JPEG_VALUE)
public HttpServletResponse getImageData(@PathVariable(PainManagementSvcApi.ID) long id,
@RequestParam(PainManagementSvcApi.IMAGE_FILE) String imageFile,
Principal principal, HttpServletResponse response) {
// Same code as before
}
但是,添加 @ResponseBody 与我拥有的工作视频示例(使用 Spring,但不使用 JPA 存储库或 WebMVC)冲突,并产生以下异常:
org.springframework.web.HttpMediaTypeNotAcceptableException: 找不到可接受的表示
除了使用 Response 返回值之外,我还尝试过返回 FileSystemResource,但这会产生如下 JSON 错误:
预期为 BEGIN_OBJECT,但在第 1 行第 1 列为 STRING
由于我只是想返回一个图像,我认为不需要 JSON,但我不知道如何删除 JSON 标头信息,因为上面的 produces 和 setContentType显然没有任何影响。此外,由于图像可能很大,我认为@Streaming 注释是有保证的,并且只能与Response 一起使用。
如果有帮助,这里是我用来测试我的应用程序的代码:
Response response = user.getImageData(extra.getId(), fileName);
assertEquals(HttpStatus.SC_OK, response.getStatus());
InputStream imageStream = response.getBody().in();
byte[] retrievedFile = IOUtils.toByteArray(imageStream);
byte[] originalFile = IOUtils.toByteArray(new FileInputStream(images[index++]));
assertTrue(Arrays.equals(originalFile, retrievedFile));
我已经在这几天了,我还没有找到任何可以建议如何克服上述问题的东西。我认为使用带有 WebMVC 的 JPA 存储库来控制对静态文件存储的访问经常出现,但我还没有找到任何有用的东西。任何帮助将不胜感激。
谢谢
【问题讨论】:
标签: java spring spring-mvc jpa