OneTwo
OneTwo

Reputation: 2483

Spring MVC: How to return an image from controller?

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>

Upvotes: 5

Views: 15630

Answers (3)

user8612465
user8612465

Reputation: 1

}

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();

Upvotes: 0

javasenior
javasenior

Reputation: 1815

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();
  }

Upvotes: 4

Jaiwo99
Jaiwo99

Reputation: 10017

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());
}

Upvotes: 2

Related Questions