4

我已经使用 Spring Data 和 GridFs 模板从 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"])
4

1 回答 1

4

如果您使用的是最新版本的spring,即Spring 4.1,我已经使用了spring boot and rest,以下代码将在其中工作

@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:如何在@ResponseBody 中返回图像?

于 2015-09-04T12:21:06.513 回答