2011-12-28 61 views
10

我在使用Spring Web Service發送圖像時遇到問題。如何在Spring中從Web服務發送圖像

我已經寫控制器如下

@Controller 
public class WebService { 

    @RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
    public @ResponseBody byte[] getImage() { 
     try { 
      InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
      BufferedImage bufferedImage = ImageIO.read(inputStream); 
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
      ImageIO.write(bufferedImage , "jpg", byteArrayOutputStream); 
      return byteArrayOutputStream.toByteArray(); 

     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

@ResponseBody轉換響應轉換JSON。

我正在使用RestClient來測試Web服務。

但是當我用http://localhost:8080/my-war-name/rest/image URL擊中時。

Header 
Accept=image/jpg 

我面臨以下錯誤上RESTClient實現

響應體轉換爲字符串使用窗口1252編碼失敗。響應主體未設置!

當我使用的瀏覽器Chrome和Firefox

頭是不添加這樣預期的錯誤(請指導我在此)

 
HTTP Status 405 - Request method 'GET' not supported 

type Status report 

message Request method 'GET' not supported 

description The specified HTTP method is not allowed for the requested resource (Request method 'GET' not supported). 

我也面臨着以下錯誤一旦

該請求所標識的資源只能夠生成具有不可接受的特徵的響應 accordi ng請求「接受」標題()

我跟着 http://krams915.blogspot.com/2011/02/spring-3-rest-web-service-provider-and.html教程。

我的需求是將圖像以字節格式發送到Android客戶端。

+0

[Spring MVC:How to return image in @ResponseBody?](http://stackoverflow.com/questions/5690228/spring-mvc-how-to-return-image-in-responsebody) – skaffman 2011-12-28 12:51:53

回答

1

將轉換轉換爲json並按原樣發送字節數組。

唯一的缺點是它默認發送application/octet-stream內容類型。

如果這並不適合你,你可以使用BufferedImageHttpMessageConverter,它可以發送任何註冊圖像閱讀器支持的圖像類型。同時具有

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
public @ResponseBody BufferedImage getImage() { 
    try { 
     InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
     return ImageIO.read(inputStream); 


    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 

:在你的Spring配置

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="order" value="1"/> 
    <property name="messageConverters"> 
     <list> 
      <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> 
     </list> 
    </property> 
</bean> 

然後你可以你的方法改變。

0

這裏是我爲此寫的方法。

我需要在頁面上內聯顯示圖像,並可選擇將其下載到客戶端,因此我採用可選參數爲其設置適當的標題。

Document是我的實體模型來表示文檔。我將文件本身存儲在以存儲該文檔的記錄的ID後命名的光盤上。原始文件名和MIME類型存儲在Document對象中。

@RequestMapping("/document/{docId}") 
public void downloadFile(@PathVariable Integer docId, @RequestParam(value="inline", required=false) Boolean inline, HttpServletResponse resp) throws IOException { 

    Document doc = Document.findDocument(docId); 

    File outputFile = new File(Constants.UPLOAD_DIR + "/" + docId); 

    resp.reset(); 
    if (inline == null) { 
     resp.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getFilename() + "\""); 
    } 
    resp.setContentType(doc.getContentType()); 
    resp.setContentLength((int)outputFile.length()); 

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(outputFile)); 

    FileCopyUtils.copy(in, resp.getOutputStream()); 
    resp.flushBuffer(); 

} 
17

除了由soulcheck提供的答案。春季已添加生產財產到@RequestMapping註釋。因此解決方案現在更容易:

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = "image/jpg") 
public @ResponseBody byte[] getFile() { 
    try { 
     // Retrieve image from the classpath. 
     InputStream is = this.getClass().getResourceAsStream("/test.jpg"); 

     // Prepare buffered image. 
     BufferedImage img = ImageIO.read(is); 

     // Create a byte array output stream. 
     ByteArrayOutputStream bao = new ByteArrayOutputStream(); 

     // Write to output stream 
     ImageIO.write(img, "jpg", bao); 

     return bao.toByteArray(); 
    } catch (IOException e) { 
     logger.error(e); 
     throw new RuntimeException(e); 
    } 
} 
+0

謝謝。有效。 – maverickosama92 2015-10-23 12:32:00

3

#soulcheck的答案部分正確。該配置在最新版本的Spring中不起作用,因爲它會與mvc-annotation元素髮生衝突。嘗試下面的配置。

<mvc:annotation-driven> 
    <mvc:message-converters register-defaults="true"> 
    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

一旦您在配置文件中具有上述配置。以下代碼將起作用:

@RequestMapping(value = "/image", headers = "Accept=image/jpeg, image/jpg, image/png, image/gif", method = RequestMethod.GET) 
public @ResponseBody BufferedImage getImage() { 
    try { 
     InputStream inputStream = this.getClass().getResourceAsStream("myimage.jpg"); 
     return ImageIO.read(inputStream); 
    } catch (IOException e) { 
     throw new RuntimeException(e); 
    } 
} 
1

請參閱this article on the excellent baeldung.com website

您可以在Spring控制器使用下面的代碼:

@RequestMapping(value = "/rest/getImgAsBytes/{id}", method = RequestMethod.GET) 
public ResponseEntity<byte[]> getImgAsBytes(@PathVariable("id") final Long id, final HttpServletResponse response) { 
    HttpHeaders headers = new HttpHeaders(); 
    headers.setCacheControl(CacheControl.noCache().getHeaderValue()); 
    response.setContentType(MediaType.IMAGE_JPEG_VALUE); 

    try (InputStream in = imageService.getImageById(id);) { // Spring service call 
     if (in != null) { 
      byte[] media = IOUtils.toByteArray(in); 
      ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(media, headers, HttpStatus.OK); 
      return responseEntity; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return new ResponseEntity<>(null, headers, HttpStatus.NOT_FOUND); 
} 

注:IOUtils來自普通-io的阿帕奇庫。我正在使用Spring服務從數據庫中檢索img/pdf Blob。

pdf文件的類似處理,除了需要在內容類型中使用MediaType.APPLICATION_PDF_VALUE。你也可以從HTML頁參考的圖像文件或PDF文件:

<html> 
    <head> 
    </head> 
    <body> 
    <img src="https://localhost/rest/getImgDetectionAsBytes/img-id.jpg" /> 
    <br/> 
    <a href="https://localhost/rest/getPdfBatchAsBytes/pdf-id.pdf">Download pdf</a> 
    </body> 
</html> 

...或者你可以直接從瀏覽器中調用Web服務方法。