springboot通过设置addResourceHandlers拦截请求访问本地资源

通过继承WebMvcConfigurationSupport(springboot2.x后用此类) 类后重写addResourceHandlers

@Configuration
public class PathConfig extends WebMvcConfigurationSupport {
    @Value("${file.upload-folder}")
    private String uploadFolder;
    @Value("${file.upload-linux}") 
    private String uploadLinux;
    @Value("${file.static-access-path}")
    private String staticAccessPath;


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String os = System.getProperty("os.name");

        //addResourceHandler是指你想在url请求的路径
        //addResourceLocations是图片存放的真实路径
        registry.addResourceHandler(staticAccessPath)
                .addResourceLocations("file:" + uploadFolder);


        //如果是Windows系统
//        if (os.toLowerCase().startsWith("win")) {
//            registry.addResourceHandler("staticAccessPath")
//                    .addResourceLocations("file:" + uploadFolder);
//        } else {  //linux 和mac
//            registry.addResourceHandler("staticAccessPath")
//                    .addResourceLocations("file:" + uploadLinux);
//        }
        super.addResourceHandlers(registry);
    }
}

 或者实现 WebMvcConfigurer

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;

/**
 * 通用映射配置
 *
 * @author arrange
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer
{
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.upload-folder}")
    private String localFilePath;

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.static-access-path}")
    public String localFilePrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        /** 本地文件上传路径 */
        registry.addResourceHandler(localFilePrefix)
                .addResourceLocations("file:" + localFilePath);
    }
}

我是通过yaml配置文件访问地址(此处坑注意访问文件路径根式正确)

file:
  #静态资源对外暴露的访问路径
  static-access-path: /static/upload/images/**
  #windows图片文件存储相对路径
  upload-folder: ${user.dir}/
  #linux系统下访问路径
  upload-linux: /user/img/


注意每个访问路径后面的路径加 / !!!

注意每个访问路径后面的路径加 / !!!

注意每个访问路径后面的路径加 / !!! 重要的事情说三遍
————————————————

原文链接:https://blog.csdn.net/qq_39025156/article/details/90055132

你可能感兴趣的:(springboot通过设置addResourceHandlers拦截请求访问本地资源)