2011-12-28 86 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服务方法。

相关问题