I need to get an image from MongoDB GridFS system, then displaying it in a JSP img tag. This is my code that isnt working:
@RequestMapping(value = "/getPhoto", method = RequestMethod.GET)
public @ResponseBody
void getPhoto(HttpServletRequest request,
HttpServletResponse response) {
try {
System.out.println("getting photo...");
GridFSDBFile imageForOutput = userFacade.loadProfilePhoto((User) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal());
BufferedImage image = ImageIO.read(imageForOutput.getInputStream());
byte[] imageBytes = ((DataBufferByte) image.getData().getDataBuffer()).getData();
response.setHeader("expires", "0");
response.setContentType("image/jpg");
response.setContentLength(imageBytes.length);
OutputStream out = response.getOutputStream();
out.write(imageBytes, 0, imageBytes.length);
out.flush();
out.close();
return;
} catch (Exception e) {
// TODO Auto-generated catch block
}
Firstly i get the GridFSDBFile and then I need to get the byte[].After that i write it in the response object but i dont know if i am doing it correctly.
The code in the JSP is as follows:
<c:url var="getPhoto" value="/settingsAdmin/getPhoto" />
<div id="preview">
<img id="imagePreview" src="${getPhoto}" alt="Profile Photo"/>
</div>
Finally, the controller is called correctly but the mistake must be inside it.
Thx in advance