有时项目导入数据时,需要拉下模板,按模板填写,近期遇到,把excel文件放在项目的resources下的file文件夹下,页面直接下载。方便以后再次遇到,直接可以使用。记录一下
首先说明获取文件的四种不同方式:
第一种:
File file = ResourceUtils.getFile("classpath:file/点位导入模板.xls");
InputStream inputStream = new FileInputStream(file);
第二种:
InputStream inputStream = this.getClass().getResourceAsStream("/file/点位导入模板.xls");
第三种:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/file/点位导入模板.xls");
第四种:
ClassPathResource classPathResource = new ClassPathResource("/file/点位导入模板.xls");
InputStream inputStream =classPathResource.getInputStream();
注意:第一种方式本地开发时可以正常读取,当打成jar包以后则,这种基于File文件的读取方式是有问题的,要用后三种,类加载的形式,具体原因待后期研究。
下载代码
@GetMapping(value = "/download")
public void downloadFile(HttpServletResponse response) {
InputStream fis = null;
OutputStream outputStream = null;
try {
// 读取文件
// InputStream inputStream =
// Thread.currentThread().getContextClassLoader().getResourceAsStream("../file/点位导入模板.xls");
InputStream inputStream = this.getClass().getResourceAsStream("/file/点位导入模板.xls");
fis = new BufferedInputStream(inputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setHeader("Content-Disposition",
"attachment;filename=" + java.net.URLEncoder.encode("点位导入模板.xls", "utf-8"));
response.addHeader("Content-Length", "" + buffer.length);
outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
log.info(e.getMessage());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
遇到的问题
用浏览器没有任何反应,用Postman测试,下载的是txt格式,因为springboot的maven默认只会加载classPath同级目录下文件(配置那些),其他的需要配置标签,修改pom文件,不过滤文件, 编译.xls文件,问题解决。
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<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>
<include>**/*.xls</include>
<include>**/*.xml</include>
</includes>
<!--是否替换资源中的属性-->
22 <filtering>false</filtering>
</resource>
</resources>
</build>
记录一下,为下次使用做个笔记