0

I am building a web app for blogging using spring boot and mongodb.I tried gridFS for storing and used input stream for storing data. But I can't return image as a model attribute.It's my controller class

@RestController
public class HomeController {

@Autowired
GridFsTemplate gridFsTemplate;

@RequestMapping(value = "/home", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> getImage() {
    GridFSDBFile gridFsFile = gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("metadata.user").is("5")));;
    InputStream inputStream = gridFsFile.getInputStream();
    System.out.println("done");
    return ResponseEntity.ok()
            .contentLength(gridFsFile.getLength())
            .contentType(MediaType.parseMediaType(gridFsFile.getContentType()))
            .body(new InputStreamResource(gridFsFile.getInputStream()));
}
}

and this is my view

<html xmlns:th="http://www.thymeleaf.org">
<head> 
</head>
<body>
<img th:src="@{/home}" />
</body>
</html>
  • Welcome to SO. You should post some of your code attempts. Otherwise you are going to get a bunch of down votes and comments saying the SO is not a code writing service. – Part_Time_Nerd Apr 21 '17 at 18:51
  • i added my code – facelesss_void Apr 21 '17 at 22:10
  • Just to clear that up - you are **not** returning an image as a model attribute anywhere in your code - what you are doing is returning the image as a response body on the `/home` endpoint. What happens when you open the `/home` endpoint in a browser? Does the image show up? – Bragolgirith Apr 21 '17 at 23:05
  • the image did not show up. I tried to return an image as a model attribute but failed. Then I followed one solution from stackoverflow. Can you help me with a sample code for returning it as a model attribute – facelesss_void Apr 22 '17 at 08:00

1 Answers1

0

You can get byte[] of image and then can write this byte array to response object. now map this method to some url. code will be something like -

  @RequestMapping(value="/imgPath")
 public void imgResponse(HttpServletResponse response){
 ServletOutputStream stream =  response.getOutputStream();
    /* get byte array and assign it to the variable dataa */
    stream.write(data);
    stream.flush();
 }

now you can provide this image in JSP like -

 <img src="./imgPath""/>
Akshay Khopkar
  • 189
  • 1
  • 2
  • 9