1. Solve the problem that SpringBoot cannot access images after uploading them.
-
Problem Description
The front-end and back-end projects are not separated.
Front-end: thymeleaf
Back-end: mybatis+springboot architecture.
After uploading the image on the front-end, upload it to the specified local path.
The path is: resources/static/upload/img/** under the idea project
has been uploaded successfully. There is also access to http://ip address:port number/path/xxx.png in the folder. Such pictures cannot be accessed. -
Cause:
The principle is caused by the protection measures of the server. The server cannot expose the real resource path to the outside, and virtual path mapping access needs to be configured. -
Solution:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// /upload/** 为虚拟地址
//file:///为真实的本地地址
registry.addResourceHandler("/upload/**").addResourceLocations("file:///"+System.getProperty("user.dir")+"/src/main/resources/static/upload/img/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
2. Second solution
spring.web.resources.static-locations=classpath:/static/,file:${
upload.dir}
upload.dir = G:/2021_12_8/easypoi_springboot/src/main/resources/static/upload/img
classpath: represents your current static resource storage location
upload.dir: represents the real path where your images are stored
http://localhost:ip/image name to access the image