Springboot下載靜態資源-excel模板
阿新 • • 發佈:2018-10-31
最近專案中要用到上傳員工資訊,在填寫員工資訊,那麼首先要定義模板且放在網站上,就要用到下載靜態資源,一般情況下實現都是如下:
1、獲取模板的路徑;(這裡的路徑經常會搞錯)
2、建立該路徑的輸入流;
3、設定response的標頭檔案格式;
4、將輸入流中的內容寫進response的輸出流中;
public void downloadExcel(HttpServletResponse response,HttpServletRequest request) { try { //獲取檔案的路徑 String excelPath = request.getSession().getServletContext().getRealPath("/Excel/"+"xx.xls"); String fileName = "xx.xls".toString(); // 檔案的預設儲存名 // 讀到流中 InputStream inStream = new FileInputStream(excelPath);//檔案的存放路徑 // 設定輸出的格式 response.reset(); response.setContentType("bin"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("xx.xls", "UTF-8")); // 迴圈取出流中的資料 byte[] b = new byte[200]; int len; while ((len = inStream.read(b)) > 0){ response.getOutputStream().write(b, 0, len); } inStream.close(); } catch (IOException e) { e.printStackTrace(); } }
但是你用了SpringBoot,那就是一句程式碼都不用敲,真是提高了開發效率,只需要把模板放在resources/static下,直接訪問就可以下載,下邊給出詳細資訊:
1、專案結構:
2、啟動專案啟動類:ExceldemoApplication;
3、在瀏覽器輸入訪問地址:http://localhost:8080/excel/xx.xlsx 並下載模板檔案如下圖所示: