Spring MVC 对文件下载做了支持, 原理为:
1.编写控制器:
/**
* 利用Spring 下载显示一张照片
*/
@RequestMapping("/image.do")
public void image(
HttpServletResponse response)
throws Exception{
//读取照片数据 到 bytes数组中
String path="D:/1.png";
byte[] bytes = readFile(path);
//设置响应头
response.setContentType("image/png");
response.setContentLength(
bytes.length);
//设置响应正文(Message Body)
OutputStream out=
response.getOutputStream();
out.write(bytes);
out.close();
}
private byte[] readFile(String path) throws FileNotFoundException, IOException {
File file=new File(path);
byte[] bytes=
new byte[(int)file.length()];
FileInputStream in=
new FileInputStream(file);
in.read(bytes);
in.close();
return bytes;
}
配置拦截器, 放过image.do请求
2.利用浏览器测试:
http://localhost:8088/spring-mvc-d2/image.do
@ResponseBody注解
Spring MVC 提供了@ResponseBody注解, 这个是一个自动处理响应Body的注解:
- 当返回值是 byte[] 时候会自动设置ContentLength, 自动填充到 响应body中.
- 当返回值是Java Bean 时候自动转换为 JSON 字符串(后面讲解)
- 还有其他功能 ...
原理:
案例:
1.编写控制器:
/**
* 利用Spring 下载显示一张照片
*/
@RequestMapping(value="/image2.do",
produces="image/png")
@ResponseBody
public byte[] image2() throws Exception{
//读取照片数据 到 bytes数组中
String path="D:/1.png";
byte[] bytes = readFile(path);
//自动设置响应头
//自动设置响应正文(Message Body)
return bytes;
}
配置拦截器, 放过image2.do请求
2.编写网页 download.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
.png{width: 200px}
</style>
</head>
<body>
<h1>下载演示</h1>
<h2>显示照片</h2>
<p>
<img class="png" alt="" src="image.do">
<img class="png" alt="" src="image2.do">
<img alt="" src="code.do">
</p>
</body>
3.测试图片的显示