一. 場景介紹
- Excel模板靜態資源在,應用中的static文件夾中,文件名稱包含中文;
- 需求:頁面直接訪問下載Excel模板.
二.目錄結構
三.后台代碼
1 @GetMapping("/downloadTemplateForUserTest") 2 @ResponseBody 3 public void downloadLocal(HttpServletResponse response) throws Exception { 4 /** 獲取靜態文件的路徑 .*/ 5 String path = ResourceUtils.getURL("classpath:").getPath() + "static/js/CRM_客戶_導入模板.xlsx"; 6 7 /** 獲取文件的名稱 . */ 8 String fileName = path.substring(path.lastIndexOf("/") +1); 9 File file = new File(path); 10 if (!file.exists()){ 11 logger.error("路徑有誤,文件不存在!"); 12 } 13 14 /** 將文件名稱進行編碼 */ 15 response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8")); 16 response.setContentType("content-type:octet-stream"); 17 BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 18 OutputStream outputStream = response.getOutputStream(); 19 byte[] buffer = new byte[1024]; 20 int len; 21 while ((len = inputStream.read(buffer)) != -1){ /** 將流中內容寫出去 .*/ 22 outputStream.write(buffer ,0 , len); 23 } 24 inputStream.close(); 25 outputStream.close(); 26 }
2019-04-19 16:49:19 -- 1.0v
二.在服務器端使用上述方法的時候,文件路徑找不到
錯誤:\C\Users\hzcuixiaoqing.m2\repository\com\netease\qa\cloudqa\nfit \0.1.0\nfit-0.1.0.jar!\cmdline_config_CPU.txt,服務器中獲取靜態文件時出現!號
分析定位原因:讀取路徑出現了"!",在網上找了很多的資料
1 @GetMapping("/downloadTemplateForUser") 2 @ResponseBody 3 public void downloadTemplateForUser(HttpServletResponse response) throws Exception { 4 String path = "/static/excel/導入到課程顧問模板.xlsx" ; 5 String fileName = path.substring(path.lastIndexOf("/") + 1); 6 downExcelTemplate(response, path, fileName); 7 return; 8 9 } 10 11 private void downExcelTemplate(HttpServletResponse response, String path, String fileName) throws IOException { 12 /** 將文件名稱進行編碼 */ 13 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); 14 response.setContentType("content-type:octet-stream"); 15 /** 讀取服務器端模板文件*/ 16 InputStream inputStream = DownloadFileController.class.getResourceAsStream(path); 17 18 /** 將流中內容寫出去 .*/ 19 OutputStream outputStream = response.getOutputStream(); 20 byte[] buffer = new byte[1024]; 21 int len; 22 while ((len = inputStream.read(buffer)) != -1) { 23 outputStream.write(buffer, 0, len); 24 } 25 inputStream.close(); 26 outputStream.close(); 27 }
使用上述的方法,可以解決服務器端的路徑問題.
2019-05-06 --v1.1