5

I'm trying to return an image like this.

 @RequestMapping(value = "admin/image/{userId}")
public ResponseEntity<byte[]> getPhoto(@PathVariable int userId) throws IOException {
    UserDB userDB = UserDBService.getUserWithId(userId);
    if (userDB != null) {
        try {
            byte[] image;
            try {
                String path = ApplicationPropertiesConstants.SAFESITE_DOCUMENTS_DIRECTORY + userDB.getSite().getId() + "\\342.png";
                InputStream is = new FileInputStream(path);
                BufferedImage img = ImageIO.read(is);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ImageIO.write(img, "png", bos);
                final HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_PNG);

                return new ResponseEntity<byte[]>(IOUtils.toByteArray(is), headers, HttpStatus.CREATED);
            } catch (FileNotFoundException e) {
                image = org.apache.commons.io.FileUtils.readFileToByteArray(new File("dfd"));
            }

            return null;
        } catch (IOException ignored) {
        }
    }
    return null;
}

Although when I access the url the image doesn't display.

enter image description here

Any idea why this is happening? Do I need to use Apache Tiles? Currently I'm using jstlView.

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
OneTwo
  • 2,291
  • 6
  • 33
  • 55

3 Answers3

4

Get your image file and write it to the response.

@RequestMapping(value = "/getImage", method = RequestMethod.GET)
  public void showImage(HttpServletResponse response) throws Exception {

    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();

    try {
      BufferedImage image = //CALL_OR_CREATE_YOUR_IMAGE_OBJECT;
      ImageIO.write(image, "jpeg", jpegOutputStream);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

    byte[] imgByte = jpegOutputStream.toByteArray();

    response.setHeader("Cache-Control", "no-store");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = response.getOutputStream();
    responseOutputStream.write(imgByte);
    responseOutputStream.flush();
    responseOutputStream.close();
  }
javasenior
  • 1,786
  • 2
  • 22
  • 26
  • Ok this worked thanks. If I know wanted to do the same but would return a file of any type (as a download link), how would I go about doing this? – OneTwo Nov 26 '15 at 13:13
  • For return any file like image, pdf or download link you must set headers. Eg: download link String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\"")); – javasenior Nov 26 '15 at 13:17
  • Pdf link response.setContentType("application/pdf"); response.setHeader("content-disposition", "inline;filename=" + "form.pdf"); – javasenior Nov 26 '15 at 13:23
2

It doesn't work this way, you need something like

@RequestMapping(...)
void getImage(...) {
  response.setContentType(mimeType);
  response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\""));
  response.setContentLength((int)file.length());
  InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  FileCopyUtils.copy(inputStream, response.getOutputStream());
}
Jaiwo99
  • 9,687
  • 3
  • 36
  • 53
  • People have definitely done it my way (returning a byte array) http://www.jadebaboon.com/wp/return-image-as-responsebody/ – OneTwo Nov 26 '15 at 12:45
  • Or see here http://stackoverflow.com/questions/5690228/spring-mvc-how-to-return-image-in-responsebody – OneTwo Nov 26 '15 at 12:47
  • 1
    @OneTwo sure, i see your problem, you should use `return new ResponseEntity(bos.toByteArray(), headers, HttpStatus.CREATED);` – Jaiwo99 Nov 26 '15 at 13:11
0

}

response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=EDC-"+ title + ".txt");
ServletOutputStream out = response.getOutputStream();
out.print(myString.trim());
out.flush();
out.close();