关于查找项目下的模板路径,我之前一直用的
getClass().getResource("/template/excel/" + fileName).getPath();
也没出啥问题,就很神奇的突然不好使了。
报错:(No such file or directory)
解决:
Resource resource = new ClassPathResource(filePath1);
resource.getInputStream();
就没有问题了。
需要注意的是,这里不能用resoutce.getFile();
因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径。 因此必须使用resource.getInputStream()
另记录一个下载的方法,方便以后使用。
public static void download(String path, HttpServletResponse response,String fileName){
path = "template/excel/" + path;
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
Resource resource = new ClassPathResource(path);
if (Objects.isNull(resource)) {
throw new BadRequestException("文件不存在");
}
// String fileName = path.split("/")[path.split("/").length - 1];
fileName = URLEncoder.encode(fileName, "utf-8");
response.setHeader("content-type", "application/octet-stream;charset=UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
// response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
// 召唤jvm的垃圾回收器
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}