首页 > 代码库 > SpringMvc文件下载

SpringMvc文件下载

 1     /**
 2      * 文件下载
 3      * @Description: 
 4      * @param fileName
 5      * @param request
 6      * @param response
 7      * @return
 8      */
 9     @RequestMapping("/download")
10     public String downloadFile(@RequestParam("fileName") String fileName,
11             HttpServletRequest request, HttpServletResponse response) {
12         if (fileName != null) {
13             String realPath = request.getServletContext().getRealPath(
14                     "WEB-INF/File/");
15             File file = new File(realPath, fileName);
16             if (file.exists()) {
17                 response.setContentType("application/force-download");// 设置强制下载不打开
18                 response.addHeader("Content-Disposition",
19                         "attachment;fileName=" + fileName);// 设置文件名
20                 byte[] buffer = new byte[1024];
21                 FileInputStream fis = null;
22                 BufferedInputStream bis = null;
23                 try {
24                     fis = new FileInputStream(file);
25                     bis = new BufferedInputStream(fis);
26                     OutputStream os = response.getOutputStream();
27                     int i = bis.read(buffer);
28                     while (i != -1) {
29                         os.write(buffer, 0, i);
30                         i = bis.read(buffer);
31                     }
32                 } catch (Exception e) {
33                     // TODO: handle exception
34                     e.printStackTrace();
35                 } finally {
36                     if (bis != null) {
37                         try {
38                             bis.close();
39                         } catch (IOException e) {
40                             // TODO Auto-generated catch block
41                             e.printStackTrace();
42                         }
43                     }
44                     if (fis != null) {
45                         try {
46                             fis.close();
47                         } catch (IOException e) {
48                             // TODO Auto-generated catch block
49                             e.printStackTrace();
50                         }
51                     }
52                 }
53             }
54         }
55         return null;
56     }

 

SpringMvc文件下载