1.jsjavascript
window.location.href = "/macModel/file/download?path="+a.download; //a.download=a.xls文件
2.controller文件java
@RequestMapping("/file/download") public void fileDownload(HttpServletResponse response, String path) { //獲取網站部署路徑(經過ServletContext對象),用於肯定下載文件位置,從而實現下載 // String path ="/Users/guanguan/workspace/rifle/static/excel/m2017_11_09_19_14_59.xls"; //1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型 response.setContentType("multipart/form-data"); String fileName = path.substring(path.lastIndexOf("/")+1); //2.設置文件頭:最後一個參數是設置下載文件名 response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); ServletOutputStream out; //經過文件路徑得到File對象 File file = new File(path); try { FileInputStream inputStream = new FileInputStream(file); //3.經過response獲取ServletOutputStream對象(out) out = response.getOutputStream(); byte[] b = new byte[100]; int len; try { while ((len = inputStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inputStream.close(); } catch (IOException e) { e.printStackTrace(); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }