代碼
10余年的尼勒克網(wǎng)站建設(shè)經(jīng)驗,針對設(shè)計、前端、開發(fā)、售后、文案、推廣等六對一服務(wù),響應(yīng)快,48小時及時工作處理。全網(wǎng)整合營銷推廣的優(yōu)勢是能夠根據(jù)用戶設(shè)備顯示端的尺寸不同,自動調(diào)整尼勒克建站的顯示方式,使網(wǎng)站能夠適用不同顯示終端,在瀏覽器中調(diào)整網(wǎng)站的寬度,無論在任何一種瀏覽器上瀏覽網(wǎng)站,都能展現(xiàn)優(yōu)雅布局與設(shè)計,從而大程度地提升瀏覽體驗。創(chuàng)新互聯(lián)從事“尼勒克網(wǎng)站設(shè)計”,“尼勒克網(wǎng)站推廣”以來,每個客戶項目都認(rèn)真落實執(zhí)行。參數(shù):
1.filePath:文件的絕對路徑(d:\download\a.xlsx)
2.fileName(a.xlsx)
3.編碼格式(GBK)
4.response、request不介紹了,從控制器傳入的http對象
代碼片.
//控制器 @RequestMapping(UrlConstants.BLACKLIST_TESTDOWNLOAD) public void downLoad(String filePath, HttpServletResponse response, HttpServletRequest request) throws Exception { boolean is = myDownLoad("D:\\a.xlsx","a.xlsx","GBK",response,request); if(is) System.out.println("成功"); else System.out.println("失敗"); } //下載方法 public boolean myDownLoad(String filePath,String fileName, String encoding, HttpServletResponse response, HttpServletRequest request){ File f = new File(filePath); if (!f.exists()) { try { response.sendError(404, "File not found!"); } catch (IOException e) { e.printStackTrace(); } return false; } String type = fileName.substring(fileName.lastIndexOf(".") + 1); //判斷下載類型 xlsx 或 xls 現(xiàn)在只實現(xiàn)了xlsx、xls兩個類型的文件下載 if (type.equalsIgnoreCase("xlsx") || type.equalsIgnoreCase("xls")){ response.setContentType("application/force-download;charset=UTF-8"); final String userAgent = request.getHeader("USER-AGENT"); try { if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Edge")) {// IE瀏覽器 fileName = URLEncoder.encode(fileName, "UTF8"); } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐瀏覽器 fileName = new String(fileName.getBytes(), "ISO8859-1"); } else { fileName = URLEncoder.encode(fileName, "UTF8");// 其他瀏覽器 } response.setHeader("Content-disposition", "attachment; filename=" + fileName); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); return false; } InputStream in = null; OutputStream out = null; try { //獲取要下載的文件輸入流 in = new FileInputStream(filePath); int len = 0; //創(chuàng)建數(shù)據(jù)緩沖區(qū) byte[] buffer = new byte[1024]; //通過response對象獲取outputStream流 out = response.getOutputStream(); //將FileInputStream流寫入到buffer緩沖區(qū) while((len = in.read(buffer)) > 0) { //使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到瀏覽器 out.write(buffer,0,len); } //這一步走完,將文件傳入OutputStream中后,頁面就會彈出下載框 } catch (Exception e) { logger.error(e.getMessage(), e); return false; } finally { try { if (out != null) out.close(); if(in!=null) in.close(); } catch (IOException e) { logger.error(e.getMessage(), e); } } return true; }else { logger.error("不支持的下載類型!"); return false; } }