您的位置:首页 > 运维架构 > 网站架构

一个jar包里的网站之返回对媒体类型

2014-05-01 22:59 1341 查看

       spring 中@ResponseBody 原样返回对象。 例如 return “hello”那就返回一个String 类型的hello ,于是我想返回图片是不是把返回值改成BufferedImage就可以了。。

       事实证明我又天真了一回,这样做肯定是不行的。

        不信的孩子可以试试。然后我又想到图片在网络中是以二进制流传输的。那么返回为byte [] 就应该可以了吧。

        以前用过restlet ,restlet中 如果要返回对象也是转化成二进制流的,servlet中也是直接out.write(byte...)关机是怎么让页面识别这个是二进制流是图片。。

        没错就是设置headers,代码如下。

        其实也可以使用produces ,看个人爱好了。。

        

@Controller

@EnableAutoConfiguration

public class ImageCtr {

@RequestMapping(value = "/imgcc", headers = "Accept=image/jpeg", method = RequestMethod.GET)

public @ResponseBody byte[] getimage() {


URL url;

BufferedImage bmg = null;

ByteArrayOutputStream bos = new ByteArrayOutputStream();

try {

url = new URL(

"http://attachments.gfan.com/forum/attachments2/day_120518/1205182052852ce273e69b7eca.jpg");

bmg = ImageIO.read(url);


ImageIO.write(bmg, "jpg", bos);

bos.flush();

} catch (Exception e) {


e.printStackTrace();

}


return bos.toByteArray();

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring boot mime
相关文章推荐