一. 场景介绍
- 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
二.在服务器端使用上述方法的时候,文件路径找不到
错误:CUsershzcuixiaoqing.m2 epositorycom eteaseqacloudqa fit .1.0nfit-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