springboot 应用中静态资源下载
一. 场景介绍
- 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!