Spring MVC:如何从控制器返回图像?

时间:2015-11-26 12:26:13

标签: spring spring-mvc

我试图返回这样的图像。

 @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;
}

虽然我访问网址时图片无法显示。

enter image description here

知道为什么会这样吗?我需要使用Apache Tiles吗?目前我正在使用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>

3 个答案:

答案 0 :(得分:4)

获取您的图像文件并将其写入响应。

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

答案 1 :(得分:2)

这不起作用,你需要像

这样的东西
@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());
}

答案 2 :(得分: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();