Gradle builds the jar package and packs the files out of the lib directory for easy reading and downloading
1. The project uses the recently popular gradle as a build tool
The framework is spring boot, and of course the project is a jar package when it runs on the server. If you deliberately open the jar package, you will find that the structure of the package is like this
2. In the project built by gradle, your project is placed in the lib directory as a jar package
As shown in the figure below,
when I download fixed files from the project, such as imported templates and other files, it is obviously undesirable and resource-consuming for us to directly read the files in the jar package through the path. And we put this file in the parent directory of the lib directory, this operation is much simpler .
3. How to modify it? We first find the gradle script file in the project
That's it
4. Add a task in it, as follows
task copyFiletemplet(type: Copy) {
from('src/main/resources/filetemplet') {
include '*'
}
into 'build/filetemplet'
dependsOn createFiletemplet
}
File as shown
5. Create a configuration item or modify an existing configuration item in gradle
distributions {
main {
baseName = "app"
version = ""
contents {
from(copyFiletemplet) {
into "filetemplet"
}
}
}
}
The baseName is the real path of your project deployment root directory. copyFiletemplet is the name of the task defined in the fourth step, and filetemplet is the file placement location I specified.
6. Then you can easily get the file to be downloaded by visiting the directory indicated by baseName + filetemplet .
Take a chestnut : In my project, the baseName is /app, and the file location is the filetemplet directory under baseName. I only need to visit the /app/filetemplet/ directory to get the files I need.
Go on the code
/**
* 下载文件模版
*
* @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);
}