前端

1
<a href="/download"> 点击下载 </a>

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@RequestMapping (value="/download")
public String downloads (HttpServletResponse response ,HttpServletRequest request) throws Exception {
// 要下载的图片地址
String path = request.getServletContext ().getRealPath ("/upload");
String fileName = "基础语法.jpg";

//1、设置 response 响应头
response.reset (); // 设置页面不缓存,清空 buffer
response.setCharacterEncoding ("UTF-8"); // 字符编码
response.setContentType ("multipart/form-data"); // 二进制传输数据
// 设置响应头
response.setHeader ("Content-Disposition",
"attachment;fileName="+URLEncoder.encode (fileName, "UTF-8"));

File file = new File (path,fileName);
//2、 读取文件 -- 输入流
InputStream input = new FileInputStream (file);
//3、 写出文件 -- 输出流
OutputStream out = response.getOutputStream ();

byte [] buff =new byte [1024];
int index=0;
//4、执行 写出操作
while ((index= input.read (buff))!= -1){
out.write (buff, 0, index);
out.flush ();
}
out.close ();
input.close ();
return null;
}