SpringMVC實現檔案下載功能(檔案匯出功能)
阿新 • • 發佈:2018-12-12
1.頁面程式碼
<a class="layui-btn" href="${pageContext.request.contextPath}/bAndWListManage/downloadWhiteListTmp.do" onclick="downloadTemplate();">模板下載</a>
2.後臺程式碼
@RequestMapping("downloadWhiteListTmp") public ResponseEntity<byte[]> downloadWhiteListTmp(HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); String fileName="importVehicleWhitelist.xls"; ServletContext servletContext = request.getServletContext(); String realPath = servletContext.getRealPath("/bwlmm/templateFiles/"+fileName); File file = new File(realPath); InputStream in; byte[] body=null; ResponseEntity<byte[]> response =null; try { in = new FileInputStream(new File(realPath)); body=new byte[in.available()];// 返回下一次對此輸入流呼叫的方法可以不受阻塞地從此輸入流讀取(或跳過)的估計剩餘位元組數 in.read(body);//讀入到輸入流裡面 fileName=new String(fileName.getBytes("gbk"),"iso8859-1");//防止中文亂碼 headers.add("Content-Disposition", "attachment;filename="+fileName); HttpStatus statusCode = HttpStatus.OK;//設定響應嗎 response =new ResponseEntity<byte[]>(body, headers, statusCode); } catch (FileNotFoundException e) { e.printStackTrace(); }//將該檔案加入到輸入流之中 catch (IOException e) { e.printStackTrace(); } return response; }
3.說明
我的檔案路徑