1 // 获取网站对象
2 ServletContext context = this.getServletContext();
3 // 获取网站资源
4 String path = context.getRealPath("/imgs/人.jpg");
5 File file = new File(path);
6 System.out.println(file);
7 // 设置响应头通知浏览器数据的处理方式
8 response.setHeader("content-disposition",
9 "attachment;filename="+
10 URLEncoder.encode(file.getName(),"utf-8")); // 处理文件名乱码 指定图片格式为下载
11 // 指定字节输入流对象
12 FileInputStream in = new FileInputStream(file);
13 // 获取字节输出流对象
14 ServletOutputStream out = response.getOutputStream();
15 // 边读边写
16 byte [] b = new byte[1024];
17 int len = 0;
18 while((len = in.read(b)) != -1){
19 out.write(b, 0, len);
20 }
21 // 释放资源
22 in.close();