前言
项目很少会将一些需要读取的文件放在项目内部,而是放在特定的文件服务器存取(系统服务器外部);但也不排除一些小项目,只有极其少量的文件读取服务(如仅仅下载一个简单的模板文件),配置文件服务器就会显得有些大材小用,就会将这些模板文件放入项目内部进行统一打包部署;
背景
一个简单的项目,用户需要根据特定格式上传一份文件进行数据导入处理,但并没有配置文件服务器什么的,只能将模板文件放入系统中读取下载;在开发环境中直接路径是可以读取(未打包),发布后发现不能读取对应的模板文件,网上搜查了一番,解决该问题。
解决方法
模板文件位置在静态目录下(直接上获取文件代码)
- 开发环境代码(开发可用,发布不可用)
/**
* 客户信息导入模板下载
*
* @return 跳转页面
*/
@GetMapping("/template_download")
@RequiresPermissions("customer:template_download")
public ResponseEntity<Resource> downloadTemplate() throws FileNotFoundException {
// Spring 自带ResourceUtils路径读取
//File file = new File("static/模板.xlsx"); // 怎么读取都是失败
File file = ResourceUtils.getFile("classpath:static/模板.xlsx");
InputStream inputStream = new FileInputStream(file);
Resource resource = new InputStreamResource(inputStream);
try {
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;fileName=" + URLEncoder.encode("客户模板.xlsx", "utf-8"))
.body(resource);
} catch (UnsupportedEncodingException e) {
log.error("文件下载异常");
throw new ExportDataException("文件下载异常");
}
}
复制代码
- 开发/发布环境(正确解法)
/**
* 客户信息导入模板下载
*
* @return 跳转页面
*/
@GetMapping("/template_download")
@RequiresPermissions("customer:template_download")
public ResponseEntity<Resource> downloadTemplate() throws FileNotFoundException {
// 直接工程内部相对路径(must)
File file = new File("src/main/resources/static/模板.xlsx");
InputStream inputStream = new FileInputStream(file);
// 使用CLASSPATH读取文件(路径必须/)
// File file = new File(this.getClass().getResource("/static/模板.xlsx").toURI());
// InputStream inputStream = this.getClass().getResourceAsStream("/static/模板.xlsx");
Resource resource = new InputStreamResource(inputStream);
try {
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;fileName=" + URLEncoder.encode("客户模板.xlsx", "utf-8"))
.body(resource);
} catch (UnsupportedEncodingException e) {
log.error("文件下载异常");
throw new ExportDataException("文件下载异常");
}
}
复制代码