1 @Controller
2 public class FileController implements ServletContextAware{
3 //Spring这里是通过实现ServletContextAware接口来注入ServletContext对象
4 private ServletContext servletContext;
5
6
7 @RequestMapping("file/download")
8 public void fileDownload(HttpServletResponse response){
9 //获取网站部署路径(通过ServletContext对象),用于确定下载文件位置,从而实现下载
10 String path = servletContext.getRealPath("/");
11 response.rset(); //清楚空格等操作
12 //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
13 response.setContentType("multipart/form-data");
14 //2.设置文件头:最后一个参数是设置下载文件名(假如我们叫a.pdf)
15 response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
16 ServletOutputStream out;
17 //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
18 File file = new File(path + "download/" + "download.pdf");
19
20 try {
21 FileInputStream inputStream = new FileInputStream(file);
22
23 //3.通过response获取ServletOutputStream对象(out)
24 out = response.getOutputStream();
25
26 int b = 0;
27 byte[] buffer = new byte[512];
28 while (b != -1){
29 b = inputStream.read(buffer);
30 //4.写到输出流(out)中
31 out.write(buffer,0,b);
32 }
33 inputStream.close();
34 out.close();
35 out.flush();
36
37 } catch (IOException e) {
38 e.printStackTrace();
39 }
40 }
41
42 @Override
43 public void setServletContext(ServletContext servletContext) {
44 this.servletContext = servletContext;
45 }
46 }