Gradle构建jar包,将文件打包到lib目录外方便读取和下载
1.项目使用了最近很火的gradle作为构建工具
框架是spring boot,项目在服务器上运行时当然是jar包了。如果你有心将jar包打开,会发现包内结构是这样的
2.在gradle构建的项目里,你的项目是作为一个jar包被放置在lib目录里的
如下图
当我相从项目里下载固定的文件,比如说导入的模版等文件时,我们通过路径直接读取jar包内的文件显然是不可取且消耗资源的。而我们将这个文件放在lib目录的父目录里,这个操作就简单的多了。
3.如何修改呢?我们先找到项目里的gradle脚本文件
就是它了
4.在其中添加一个任务,如下
task copyFiletemplet(type: Copy) {
from('src/main/resources/filetemplet') {
include '*'
}
into 'build/filetemplet'
dependsOn createFiletemplet
}
文件如图所示
5.创建一个配置项或者修改gradle里已有的配置项
distributions {
main {
baseName = "app"
version = ""
contents {
from(copyFiletemplet) {
into "filetemplet"
}
}
}
}
其中baseName是你的项目部署根目录真实路径。 copyFiletemplet是我第四步定义的任务名称,filetemplet是我指定的文件放置位置。
然后可以通过访问 baseName + filetemplet 所表示的目录轻松的获取到要下载的文件了。
举个栗子:我项目里baseName为 /app ,文件放置位置为 baseName下的 filetemplet目录 ,我 只需访问 /app/filetemplet/ 目录就能获取到我所需的文件了
上代码吧
/**
* 下载文件模版
*
* @param response Http响应
* @param fileName 浏览器显示文件名
* @param fileRealName 项目内文件名称
*/
@SneakyThrows
public static void downloadFiletemplet(HttpServletResponse response, String fileName, String fileRealName) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1")); // 中文文件名处理
response.addHeader("Content-Type", "application/vnd.ms-excel");
String getName;
//如果不是linux系统就是本地下载
if ((!System.getProperties().getProperty("os.name").toLowerCase().contains("linux"))) {
getName = System.getProperty("user.dir").concat("/build/resources/main/filetemplet/").concat(fileRealName);
} else {
getName = "/app/filetemplet/".concat(fileRealName);
}
log.info("下载文件 {}",getName);
@Cleanup InputStream inputStream = new FileInputStream(new File(getName));
OutputStream os = response.getOutputStream();
IOUtils.copy(inputStream, os);
}