SpringBoot读取Resource下文件的几种方式(十五)

需求:提供接口下载resources目录下的模板文件,(或者读取resources下的文件)给后续批量导入数据提供模板文件。

方式一:ClassPathResource

//获取模板文件:注意此处需要配置pom.xml文件;因为spring-boot默认只会读取application.yml配置文件
ClassPathResource classPathResource = new ClassPathResource(examplePath);
File file = null;
try {
file= classPathResource.getFile();
} catch (IOException e) {
e.printStackTrace();
}

模板文件位置

SpringBoot读取Resource下文件的几种方式(十五)

坑1:找不到模板文件staffTemplate.xlsx。
原因:maven默认只编译默认配置文件格式的文件,如yml。
解决:pom.xml 增加下面配置

 <build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.xlsx</include>
</includes>
</resource>
</resources>
</build>

坑2:中文文件名下载后无法正常显示。
解决:将中文编码


response.setHeader("Content-Disposition", "attachment;fileName=批量上传用户模板.xlsx");
//String fileName=new String("批量上传用户模板".getBytes(), StandardCharsets.ISO_8859_1);
改为
response.setHeader("Content-Disposition", "attachment;fileName=" + new String("批量上传用户模板".getBytes(), StandardCharsets.ISO_8859_1)
+ ".xlsx");

参考链接:https://blog.csdn.net/weixin_42410936/article/details/106126377

问题:我通过这种方式,在本地可以找到路径,升到测试环境就不可以了。

上一篇:【运维】略谈Raid级别


下一篇:阿里云“网红"运维工程师白金:做一个平凡的圆梦人