1 // 1.获取要下载的文件的绝对路径
2 String realPath = this.getServletContext().getRealPath("/download/泉州行政区图0.jpg");
3 System.out.println(realPath);
4 // 2.获取要下载的文件名
5 String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
6 // 3.设置content-disposition响应头控制浏览器弹出保存框,若没有此句则浏览器会直接打开并显示文件。中文名要经过URLEncoder.encode编码,否则虽然客户端能下载但显示的名字是乱码
7 response.setHeader("content-disposition", "attachment;filename=hehe" + URLEncoder.encode(fileName, "UTF-8"));
8 // 4.获取要下载的文件输入流
9 InputStream in = new FileInputStream(realPath);
10 int len = 0;
11 // 5.创建数据缓冲区
12 byte[] buffer = new byte[1024];
13 // 6.通过response对象获取OutputStream流
14 OutputStream out = response.getOutputStream();
15 // 7.将FileInputStream流写入到buffer缓冲区
16 while ((len = in.read(buffer)) > 0) {
17 // 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
18 out.write(buffer, 0, len);
19 }
20 }