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

猜你喜欢

转载自www.cnblogs.com/djq-jone/p/10737946.html