java – 浏览器显示jpeg的原始图像数据.我应该确保在响应中有哪
我似乎遇到一个有趣的问题,浏览器很高兴地显示我的
Spring MVC Web应用程序生成的图像,只要我的控制器的URL设置为IMG标签的SRC,但在直接导航到URL时显示二进制数据.
我的Spring MVC控制器生成一些BufferedImage(缩略图),将其转换为byte [],并使用控制器方法上的@ResponseBody注释将其直接返回到响应体.我已经注册了一个org.springframework.http.converter.ByteArrayHttpMessageConverter消息转换器与AnnotationMethodHandlerAdapter,甚至将其supportedMediaTypes属性设置为image / jpeg,这不是真正的帮助,所以我正在手动设置响应的Content-Type头控制器方法. <img src="/images/thumbnail?id=1234" /> 工作正常并显示图像,但直接导航到图像的SRC(或右键单击图像并选择查看图像)最终显示图像的原始数据. Firebug根据对这样的URL(http:// localhost:8888 / images / thumbnail?id = F0snPkvwhtDbl8eutbuq)的请求收到的响应标头是: HTTP/1.1 200 OK Expires: Wed,21 Dec 2011 12:39:07 GMT Cache-Control: max-age=2592000 Content-Type: image/jpeg Content-Length: 6998 Server: Jetty(6.1.10) 最后一句话:在Firebug中,单击“响应”选项卡显示图像:-)我错过了什么?我以为浏览器接收到内容类型和内容长度标题,知道要jpeg图像,接收jpeg的原始数据,然后在空的浏览器标签中显示jpeg.不知何故FF和Chrome正在显示收到的原始图像数据. 我使用的代码: @RequestMapping(value = "thumbnail",method = { RequestMethod.GET }) @ResponseBody public byte[] getImageThumbnail(@RequestParam("id") String documentId,HttpServletResponse response) { try { Document document = documentService.getDocumentById(documentId); InputStream imageInputStream = new FileInputStream(document.getUri()); response.setContentType("image/jpeg"); BufferedImage img = ImageIO.read(imageInputStream); ResampleOp resampleOp = new ResampleOp(THUMBNAIL_DIMENSION); BufferedImage thumbnail = resampleOp.filter(img,null); return getDataFromBufferedImage(thumbnail); } catch (Throwable t) { return null; //return no data if document not found or whatever other issues are encountered } } private byte[] getDataFromBufferedImage(BufferedImage thumbnail) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(thumbnail,"jpg",baos); baos.flush(); return baos.toByteArray(); } finally { baos.close(); } } ===更新=== 编辑 附加信息 编辑 解决方法
尝试将您的注释更新为:
@RequestMapping(value = "thumbnail",method = { RequestMethod.GET },produces = {"image/jpeg"}) @ResponseBody 注意产生属性. 希望有帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |