java 实现对指定目录的文件进行下载

 1      @RequestMapping("/exportDocument")
 2      @ResponseBody
 3      public void exportDocument(HttpServletRequest request,HttpServletResponse response) throws IOException {    
 4         XWPFDocument xdoc = null;
 5         FileInputStream is = null;
 6         OutputStream out=null; 
 7         try {
 8             String wordName="数聚空港2.0使用手册.docx";
 9             wordName = new String(wordName.getBytes(), "iso8859-1");
10             // File file = new File("/root/usersGuide.docx"); 
11             response.setContentType("APPLICATION/OCTET-STREAM");
12             response.setHeader("Content-Disposition", "attachment; filename="+ wordName);
13             is = new FileInputStream("/root/usersGuide.docx");
14             out=response.getOutputStream();//获得一个output对象
15             xdoc = new XWPFDocument(is);
16             } catch (IOException e) {
17                 e.printStackTrace();
18             }finally{
19                 try {
20                     xdoc.write(out);//Write out this document to an Outputstream.
21                     is.close();
22                     out.close();
23                 } catch (IOException e) {
24                     e.printStackTrace();
25                 }
26             }
27             /*上述是word文档的下载*/
28 
29 
30             /*下面是对各种类型的文件下载*/
31         
32                  /*
33   
34           //2.获取要下载的文件名
35                 String fileName = "test.png";
36                 //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
37                 response.setHeader("content-disposition", "attachment;filename="+fileName);
38                 //4.获取要下载的文件输入流
39                 InputStream in=null;
40                 OutputStream out=null;
41                 try {//获取要下载的文件的绝对路径
42                     in=new FileInputStream("/root/运营线路图0.3.5版.png");
43                     int len = 0;
44                      //5.创建数据缓冲区
45                      byte[] buffer = new byte[1024];
46                      //6.通过response对象获取OutputStream流
47                      out = response.getOutputStream();
48                      //7.将FileInputStream流写入到buffer缓冲区
49                      while ((len = in.read(buffer)) > 0) {//in.read(byte[] b)最多读入b.length个字节 在碰到流的结尾时 返回-1
50                      //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
51                          out.write(buffer,0,len);
52                      }
53                  }catch (FileNotFoundException e) {
54                     e.printStackTrace();
55                  }finally{
56                      in.close();
57                      out.close();
58                  }*/            
59     }          

 

posted @ 2017-06-09 10:26  小梅子呀  阅读(9619)  评论(1编辑  收藏  举报