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

时间:2015-09-04 09:34:54

标签: java spring mongodb rest gridfs-stream

我使用Spring Data和GridFs Template

从Mongo DB中检索了图像

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

  
    

假设他们要求http://host.com/apple作为春季休息电话。     现在,我的应用程序使用名称 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"])

1 个答案:

答案 0 :(得分:3)

如果您使用的是最新版本的弹簧,我使用了弹簧靴和休息,以下代码将起作用,即 Spring 4.1

@RequestMapping(value = "/image", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<InputStreamResource> getImage() {
        GridFSDBFile gridFsFile = App.getImageResponse();

        return ResponseEntity.ok()
                .contentLength(gridFsFile.getLength())
                .contentType(MediaType.parseMediaType(gridFsFile.getContentType()))
                .body(new InputStreamResource(gridFsFile.getInputStream()));
    }

我关注这篇文章,退房。 Spring MVC: How to return image in @ResponseBody?