2015-09-04 1 views
3

Я получил изображение из Mongo DB с использованием Spring Data и GridFs TemplateКак отправить полученное изображение из Mongo, используя GridFS в Spring Rest Call?

, так что я не знаю, как вернуть этот загруженный входной поток пользователю.

Say они просили для http://host.com/apple в весеннего отдыха вызова а. Теперь мое приложение обрабатывает запрос, используя имя apple оно извлекает изображение яблока из базы данных mongodb. Теперь без сохранения в любом месте я хочу отобразить ответ как изображение для пользователя, которое покажет http://host.com/apple изображение в браузере. Как именно мне нужно это реализовать?

Не могли бы вы поделиться какой-либо репозиторий кода для обработки запроса изображения в Rest Зов?

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

Я использовал ботинок пружины и отдыха, где этот следующий код будет работать если вы используете последнюю версию весны, то есть 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?

Смежные вопросы