resource文件下载时需要获取文件目录其中有如下几种方式获取文件目录
- 直接获取input流(该方法只能获取到resource下的,不能获取到resource更下一级目录的文件)
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("文件名");
- spring提供的方法
String filename = "导入模板.xls";
String path = "excel/bbb.xls";
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);
pom文件配置
<plugins>
<!-- 避免excel文件压缩破坏 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
下载文件
/**
* 下载文件
*
* @param response 请求头
* @param fileName 文件名
* @param filePath resource下文件路径:path/fileName.xlsx
*/
public static void downloadFile(HttpServletResponse response, String fileName, String filePath) throws IOException {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
writeData(is, response.getOutputStream());
}
public static void writeData(InputStream is, OutputStream os) {
try {
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}