springboot下载resources目录下的excel文件
1. 编写下载接口
@GetMapping(value = "/download")
public void downloadFile(HttpServletResponse response) {
// 以流的形式下载文件。
try {
//读取文件
InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("file/批量导入标准模板.xls");
InputStream fis = new BufferedInputStream(resourceAsStream);
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-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
log.info(e.getMessage());
}
}
2. 遇到的坑
2.1.读取文件失败,报错文件没找到
查看pom文件中的配置,改成如下,发现可以读取文件,但是下载的文件乱码
这个配置是通过maven将文件打包到jar包里面
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>*/*.*</include>
<include>*/*.xls</include>
</includes>
</resource>
</resources>
查看target目录下的文件,发现里面的文件也是乱码
2.2 修改pom文件配置,不过滤xls文件
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>mappers/*.*</include>
<include>application.properties</include>
<include>logback-spring.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xls</include>
</includes>
</resource>
</resources>
重启,调用接口,下载文件没有乱码