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 }