您的位置:首页 > 编程语言 > Java开发

spring mvc 通过字节流返回图像

2015-07-15 15:07 495 查看

需求:

通过一个请求url返回一张图片

例如



这样有一个好处是,你发你的请求.但是你就是不知道我的实际图片在哪儿?呵呵好耍三

代码




View
Code

/**
* 通过url请求返回图像的字节流
*/
@RequestMapping("icon/{cateogry}")
public void getIcon(@PathVariable("cateogry") String cateogry,
HttpServletRequest request,
HttpServletResponse response) throws IOException {

if(StringUtils.isEmpty(cateogry)) {
cateogry = "";
}

String fileName = request.getSession().getServletContext().getRealPath("/")
+ "resource\\icons\\auth\\"
+ cateogry.toUpperCase().trim() + ".png";

File file = new File(fileName);

//判断文件是否存在如果不存在就返回默认图标
if(!(file.exists() && file.canRead())) {
file = new File(request.getSession().getServletContext().getRealPath("/")
+ "resource/icons/auth/root.png");
}

FileInputStream inputStream = new FileInputStream(file);
byte[] data = new byte[(int)file.length()];
int length = inputStream.read(data);
inputStream.close();

response.setContentType("image/png");

OutputStream stream = response.getOutputStream();
stream.write(data);
stream.flush();
stream.close();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: