我在我的控制器中使用Spring 3.2.11和以下方法。
@RequestMapping(value = "/screenshot")
public ResponseEntity getScreenshot() {
InputStream is = getPngFileInputStream();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
byte[] bytes = IOUtils.toByteArray(is);
FileUtils.writeByteArrayToFile(
new File("/tmp/screenshot-debug.png"), bytes);
return new ResponseEntity<byte[]>(bytes, headers,HttpStatus.OK);
}
我希望将图像作为原始字节传输,但这是我得到的输出:
$ curl 'http://localhost/.../screenshot' -v > /tmp/image.png
< Date: Wed, 10 Feb 2016 03:50:48 GMT
< Server: Apache-Coyote/1.1
< Content-Type: image/png;charset=UTF-8
< Transfer-Encoding: chunked
$ ls -l /tmp/*.png
-rw-r--r-- 1 oracle dba 54978 Feb 9 20:05 /tmp/image.png
-rw-r--r-- 1 tomcat tomcat 41231 Feb 9 20:05 /tmp/screenshot-debug.png
$ file /tmp/image.png
/tmp/image.png: ASCII text, with very long lines, with no line terminators
$ file /tmp/screenshot-debug.png
/tmp/screenshot-debug.png: PNG image data, 1600 x 2560, 8-bit/color RGB, non-interlaced
因此,似乎字节[]被编码为ASCII文本,使其无法使用。 怎么可能出错?如何从服务返回原始字节流?
提前致谢!
答案 0 :(得分:3)
而不是
new ResponseEntity<byte[]>(bytes, headers,HttpStatus.OK);
尝试使用
new ResponseEntity<Resource>(
new ByteArrayResource(bytes), headers, HttpStatus.OK);
答案 1 :(得分:0)
通过将mvc命名空间添加到我的bean配置来解决 和注释驱动元素。毕竟一定是转换器。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">`
<mvc:annotation-driven/>
</beans>`
如果没有这个,即使是普通的html文本也会在返回浏览器之前被引用。