2015-11-26 109 views
2

我想要返回這樣的圖像。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; 
} 

儘管當我訪問url時圖片不顯示。

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> 
+0

你什麼反應? – zeroflagL

+0

無法加載響應數據 – OneTwo

+0

如果您有'InputStream',無論如何您可以返回一個'ResponseEntity ',其主體是'new InputStreamResource(inputStream)'。 – zeroflagL

回答

3

讓您的圖像文件,並將其寫入響應。

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

好吧,這工作的感謝。 如果我知道要做同樣的事情,但會返回任何類型的文件(作爲下載鏈接),我該如何去做這件事? – OneTwo

+0

要返回任何文件,如圖片,pdf或下載鏈接,您必須設置標題。例如:下載鏈接String mimeType =「application/octet-stream」; response.setContentType(mime類型); response.setHeader(「Content-Disposition」,String.format(「inline; filename = \」「+ file.getName()+」\「」)); – javasenior

+0

Pdf鏈接 response.setContentType(「application/pdf」); response.setHeader(「content-disposition」,「inline; filename =」+「form.pdf」); – javasenior

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

人們已經明確地按照我的方式完成了它(返回一個字節數組) http://www.jadebaboon.com/wp/return-image-as-responsebody/ – OneTwo

+0

或在這裏看到http://stackoverflow.com/questions/5690228/spring-mvc-how-to-return -image-in-responsebody – OneTwo

+0

@One確定,我看到你的問題,你應該使用'return new ResponseEntity (bos.toByteArray(),headers,HttpStatus.CREATED);' – Jaiwo99

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

你能解釋一下你的代碼嗎? –

+0

請添加一些細節和解釋,以便幫助他人 –

相關問題