一. 场景介绍
- Excel模板静态资源在,应用中的static文件夹中,文件名称包含中文;
- 需求:页面直接访问下载Excel模板.
二.目录结构
三.后台代码
@GetMapping("/downloadTemplateForUserTest")
@ResponseBody
public void downloadLocal(HttpServletResponse response) throws Exception {
/** 获取静态文件的路径 .*/
String path = ResourceUtils.getURL("classpath:").getPath() + "static/js/CRM_客户_导入模板.xlsx"; /** 获取文件的名称 . */
String fileName = path.substring(path.lastIndexOf("/") +1);
File file = new File(path);
if (!file.exists()){
logger.error("路径有误,文件不存在!");
} /** 将文件名称进行编码 */
response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.setContentType("content-type:octet-stream");
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1){ /** 将流中内容写出去 .*/
outputStream.write(buffer ,0 , len);
}
inputStream.close();
outputStream.close();
}
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,服务器中获取静态文件时出现!号
分析定位原因:读取路径出现了"!",在网上找了很多的资料
@GetMapping("/downloadTemplateForUser")
@ResponseBody
public void downloadTemplateForUser(HttpServletResponse response) throws Exception {
String path = "/static/excel/导入到课程顾问模板.xlsx" ;
String fileName = path.substring(path.lastIndexOf("/") + 1);
downExcelTemplate(response, path, fileName);
return; } private void downExcelTemplate(HttpServletResponse response, String path, String fileName) throws IOException {
/** 将文件名称进行编码 */
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("content-type:octet-stream");
/** 读取服务器端模板文件*/
InputStream inputStream = DownloadFileController.class.getResourceAsStream(path); /** 将流中内容写出去 .*/
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
}
使用上述的方法,可以解决服务器端的路径问题.
2019-05-06 --v1.1