Solve the problem that SpringBoot cannot access images after uploading them in the springboot project

1. Solve the problem that SpringBoot cannot access images after uploading them.

  1. 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.

  2. 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.

  3. 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
Insert image description here

Guess you like

Origin blog.csdn.net/wyr1235/article/details/130294891