Solve the problem of Spring Boot accessing static resources in the resources directory (detailed version)

1. Solve the problem of Spring Boot accessing static resources in the resources directory

The following analyzes access and uploads the contents of the static directory from the two aspects of reading and writing

1.2 Read

Reading resources (that is, accessing static resources on the web) is actually very simple. Spring Boot is configured with /static/** mapping by default, so it can be accessed without any configuration. However, it should be noted that if a template engine (such as thymeleaf) is used, manual configuration is required. The following demonstrates two ways to access static resources through the template engine:

  • Directly put resources in the templates directory, and then you can access them by path, because by default, you will find static resources in the templates directory
    insert image description here

    Visit hello.html directly: localhost:8080/hello.html
  • If you want to directly access resource/static, you need to add the following configuration in application.yml, otherwise 404 will appear

    spring:
      mvc:
        static-path-pattern: /static/**
    

2. Write

It is also called uploading resources. In fact, it is not recommended to directly write business-related files (especially stored pictures) in the resources directory, because you may encounter

  • Real-time resource access problems, such as uploading pictures and then accessing them, may require restarting to continue accessing
  • jar protects the resources directory, and the uploaded resources may not be read

However, there are very few files that need to be stored in the resources directory, so you need to obtain the corresponding directory under resources first. At this time, you should consider that there will be no errors when running the jar package in the future, so I recommend two ways to obtain the static directory:

  • Obtain the static directory through the ResourceUtils tool

    try {
          
          
    File staticDir = new File (ResourceUtils.getURL("classpath:static").getPath());
    } catch (FileNotFoundException e) {
          
          
        // static 目录不存在!
        e.printStackTrace();
    }
    
  • Get it through ClassPathResource

    // 这里要具体到你要访问的文件,然后拿到文件流对象,你就可以放肆操作了!
    ClassPathResource classPathResource = new ClassPathResource("/static/xxx/xxx.png");
    InputStream inputStream = classPathResource.getInputStream();
    // 转成字节数组
    final byte[] bytes = IOUtil.toByteArray(inputStream);
    // 比如把图片装成 base64 编码的字符串
    String imgStr = "data:image/png;base64, " + Base64.getEncoder().encodeToString(bytes);
    

1.3 Summary

Finally, I would like to say that if you want to upload pictures, it is best not to upload pictures directly in the jar package. You should consider:

  • To build a dedicated static resource server (image server) you can use nginx

  • Secondly, you can consider making a mapping directory on the local hard disk:

    Add the configuration file WebMVCConfig, and then add resource mapping:

    @Slf4j
    @Configuration
    public class WebMVCConfig implements WebMvcConfigurer {
          
          
        
        @Value("${logo-img.request-path}")
        private String logoReqPath; // 请求地址
        @Value("${logo-img.local-path}")
        private String logoLocPath; // 本地存放资源目录的绝对路径
    	
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
          
          
            File logoDir = new File(logoLocPath);
            boolean flag = false;
            if (!logoDir.exists())
                flag = logoDir.mkdirs();
            if (flag)
                log.info("已成功创建资源 logo 目录:{}", logoLocPath);
    
            log.info("getAbsolutePath = {}", logoDir.getAbsolutePath());
            log.info("getPath = {}", logoDir.getPath());
            
            registry.addResourceHandler(logoReqPath)
                    .addResourceLocations("file:" + logoDir.getAbsolutePath() + File.separator);
        }
    }
    

    The above parameters are configured in application.yml as follows:
    insert image description here

    The last access /logo-view-s/xxx.pngto will map toD:/test/logos/xxx.png

Guess you like

Origin blog.csdn.net/dubulingbo/article/details/122105876