2

I have a Spring MVC application, and one of the JSPs must show images coming from a database.

The images are stored in the DB as Blobs.

What is the easiest way to display them? What kind of servlet/controller do I need to show on the JSP the image bytes? Should be an easy question, but I haven't been able to find a full solution anywhere.

My understanding is that I need a separate controller, say ImgController/id=, which will display the image bytes based on a request parameter, and then in my JSP I can have img src="ImgController/id...". But how do I implement and wire this controller?

Any help or example would be really appreciated. Thanks a lot.

2
  • A simple solution I found is to have a plain Servlet (not an MVC Controller, but just an HttpServlet) to serve the image, based on the request param (ID). However, in this case we go outside of the SpringMVC Container, and automatic DB access is out of reach. So I put into the Session a HashMap (ID->Blob) that gets set from some initial SpringMVC Controller that does have access to the DB. With this session attribute publicly available, the ImgServlet can get the bytes without going to the DB. It works. But a proper SpringMVC solution would be nice. Commented Jul 7, 2011 at 3:40
  • Are you planning on using Spring's MVC annotations or extend one of the deprecated classes in org.springframework.web.servlet.mvc such as AbstractController? Commented Jul 7, 2011 at 4:17

2 Answers 2

8

The simplest solution (in terms so writing as less as possible) is a Spring MVC Controller Method with return Type OutputStream or ResponseEntity.

I prefer: return a ResponseEntity:

@RequestMapping(value = "/reportTemplate/{id}/content", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadReportTemplateContent(
        @PathVariable("id") final ReportTemplate reportTemplate)
        throws IOException {
    ReportDatei file = reportTemplate.getFile();

    String fileName = reportTemplate.getName() + EXCEL_FILE_NAME_ENDING;
    HttpHeaders responseHeaders = httpHeaderExcelFileAttachment(fileName,
                                    datei.getDaten().length);
    return new ResponseEntity<byte[]>(file.getDataArray(),
                                      responseHeaders, HttpStatus.OK);
}


public static HttpHeaders httpHeaderExcelFileAttachment(final String fileName,
        final int fileSize) {
    String encodedFileName = fileName.replace('"', ' ').replace(' ', '_');

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
    responseHeaders.setContentLength(fileSize);
    responseHeaders.set("Content-Disposition", "attachment");
    responseHeaders.add("Content-Disposition", "filename=\"" + encodedFileName + '\"');
    return responseHeaders;
}

But there are many more:

Use HttpServletResponse directly

@RequestMapping(value = "/document/{id}/fileContent", method = RequestMethod.GET)
    public void getDocumentFileContent(final HttpServletResponse response,
            @PathVariable("id") final Document document)
            throws IOException {
        FileContentUtil.writeFileContentToHttpResponse(document.getFile(),
                        response, this.fileService);
    }

    public static void writeFileContentToHttpResponse(final CommonFileInfo fileInfo,
              final HttpServletResponse response,
              final FileService fileService) throws IOException {
        String mimeType = fileInfo.getMimeType() != null ? fileInfo.getMimeType() : CommonFileInfo.DEFAULT_MIME_TYPE;
        String fileName = fileInfo.getOriginalName().replace('"', ' ');

        FileContent fileContent = fileService.loadFileContent(fileInfo.getFileContentBusinessId());
        response.setContentType(mimeType);
        response.setContentLength(fileInfo.getSize());
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + '"');

        response.getOutputStream().write(fileContent.getContent());
        response.getOutputStream().flush();
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it really helped me to return image from controller to <img> :)
2

I have compiled some code here!

Please have a look and let me know if that fits your case. I think this should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.