如何在Spring Rest Call中使用GridFS从Mongo发送检索到的图像?

我使用Spring Data和GridFs Template从Mongo DB中检索了图像

所以我不知道如何将检索到的输入流提供给用户。

假设他们要求http://host.com/apple作为春季rest电话 。 现在我的应用程序使用名称apple处理请求,它从mongodb数据库中检索苹果图像。 现在没有保存在任何地方我想将响应显示为用户的图像,将在浏览器中显示http://host.com/apple图像。 我究竟需要如何实现这个?

你可以分享任何代码库来处理Rest Call中的图像请求吗?

Controller Code

  @RestController public class GreetingController { @RequestMapping("/image") public GridFSDBFile imageReponse() { App.getImage(); return App.getImageResponse(); } } 

此函数将从mongodb中获取图像

 public static GridFSDBFile getImageResponse() { try { ApplicationContext context = new FileSystemXmlApplicationContext( "file:C:\\workspace\\gs-rest-service-complete\\spring-config.xml"); FileStorageDao fileStorageDao = (FileStorageDao) context .getBean("fileStorageDao"); GridFSDBFile retrive = fileStorageDao.retrive("audi.jpg"); return retrive; } catch (Exception e) { System.out.println("IOException:-" + e.getMessage()); } finally { System.out.println("Clean up herer:-"); } return null; } 

错误

 Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri Sep 04 17:21:05 IST 2015 There was an unexpected error (type=Internal Server Error, status=500). Could not write content: No serializer found for class com.mongodb.gridfs.GridFSDBFile$MyInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.mongodb.gridfs.GridFSDBFile["inputStream"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.mongodb.gridfs.GridFSDBFile$MyInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.mongodb.gridfs.GridFSDBFile["inputStream"]) 

我已经使用了弹簧引导和rest,如果您使用的是最新版本的弹簧,即Spring 4.1 ,则以下代码将起作用

 @RequestMapping(value = "/image", method = RequestMethod.GET) @ResponseBody public ResponseEntity getImage() { GridFSDBFile gridFsFile = App.getImageResponse(); return ResponseEntity.ok() .contentLength(gridFsFile.getLength()) .contentType(MediaType.parseMediaType(gridFsFile.getContentType())) .body(new InputStreamResource(gridFsFile.getInputStream())); } 

我关注这篇文章,退房。 Spring MVC:如何在@ResponseBody中返回图像?

Interesting Posts