@RequestMapping(value = "/image/get")
public void getImage(HttpServletRequest request,HttpServletResponse response) {
FileInputStream fis = null;
response.setContentType("image/gif");
try {
OutputStream out = response.getOutputStream();
File file = new File("D:"+File.separator+"timg.jpg");
fis = new FileInputStream(file);
byte[] b = new byte[fis.available()];
fis.read(b);
out.write(b);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
问题扩展:
为什么不能使用FileOutputStream来读取文件,也就是不能将用char[]来输出文件?
答:因为是由于要使用二进制来传输文件吧!!
小结:
Spring强大支出不仅有很多好处,可以无缝的和Servlet相结合,不会像Struts2自己还封装了一层。
<img src="/logImage/img.json">
|
转:http://my.oschina.net/jast90/blog/294868
|

本文展示了一个使用Spring MVC框架输出图片的示例代码,并解释了为何不能使用FileOutputStream进行文件读取。通过该示例,读者可以了解如何正确地在Web应用中处理并返回图片数据。
1710

被折叠的 条评论
为什么被折叠?



