Springboot project can't find the solution of static resources under resource by typing war package and docker package
- 2021-07-09 08:20:25
- OfStack
I encountered a problem in the previous period of time, which was about reading file resources in the project. I am an maven project, I put a photo under resource, and then read it locally, but I always find a file resource error when I make an WAR package. My war package is an war package made by springboot, which is embedded tomcat, so it is not decompressed. Then when the system finds the path, it will find that it is an WAR package, and the picture is in WAR package, so it cannot be found.
In order to solve this problem, I took many detours and spent time on the path.
1 Start using the method of modifying configuration files:
# Configuring static resource access prefixes
spring.mvc.static-path-pattern=*/**
# Configure static resource path, default configuration fails
spring.resources.static-locations=../upload
Discovery is not good, and the relative path cannot be resolved.
Finally, I read the file source through the system operation, then store the file stream on the server, store a temporary file, and then the system reads the temporary file again, and then reads the file.
In fact, the java data stream is converted into a file
The idea of solving problems is as above. Then there is the code
The calling code is as follows
File f = new File("/tmp/image1.jpg"));// Where the temporary picture exists
if (!f.exists()) {
InputStream in = this.getClass().getResourceAsStream("/templates/emailImg.png");// The position of the picture in the project
FileUtil.inputstreamtofile(in, f);
}
// If you need to use files, this /tmp/image1.jpg Is the temporary file path
The conversion method code is as follows
public static void inputstreamtofile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note that under 1, the path where temporary files are placed may be in the docker container, not on the server. Therefore, you need to put the previous path first
mkdirs
, and then
f.createNewFile;
, and then call at 1
FileUtil.inputstreamtofile
To be able to.
Summarize