首先強調,需要下載的文件只能放在項目中的webapp下
1、頁面的一個超鏈接,鏈接到controller
<a href="<%=path%>/download">點擊下載文件</a>
2、controller中的代碼:
@RequestMapping("/download") @ResponseBody public void downLoadExcelModel(HttpServletRequest request,HttpServletResponse response) throws Exception { String download = request.getSession().getServletContext().getRealPath("/upload/"); //獲取下載路勁 ExcelAndCsvDownload.downLoadFile(moban.csv,csv,download, response);//依次傳入需要下載的文件名,文件格式,路徑,response參數 }
3、工具類:
package com.common.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import javax.servlet.http.HttpServletResponse; public class ExcelAndCsvDownload{ public static boolean downLoadFile(String name,String type,String path,HttpServletResponse response) throws Exception { String fileName = name; String fileType = type; File file = new File(path+fileName); //根據文件路徑獲得File文件 //設置文件類型(這樣設置就不止是下Excel文件了,一舉多得) if("pdf".equals(fileType)){ response.setContentType("application/pdf;charset=GBK"); }else if("csv".equals(fileType)){ response.setContentType("application/msexcel;charset=GBK"); }else if("doc".equals(fileType)){ response.setContentType("application/msword;charset=GBK"); }else if("xls".equals(fileType)){ response.setContentType("application/msexcel;charset=GBK"); } //文件名 response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(fileName.getBytes(), "ISO8859-1") + "\""); response.setContentLength((int) file.length()); byte[] buffer = new byte[4096];// 緩沖區 BufferedOutputStream output = null; BufferedInputStream input = null; try { output = new BufferedOutputStream(response.getOutputStream()); input = new BufferedInputStream(new FileInputStream(file)); int n = -1; //遍歷,開始下載 while ((n = input.read(buffer, 0, 4096)) > -1) { output.write(buffer, 0, n); } output.flush(); //不可少 response.flushBuffer();//不可少 } catch (Exception e) { //異常自己捕捉 } finally { //關閉流,不可少 if (input != null) input.close(); if (output != null) output.close(); } return false; } }