SpringBoot图片上传访问路径

1.使用环境

SpringBoot2.7.5

2.资源映射

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    @Value("${custom.file.path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/img/**") //资源访问路径
                .addResourceLocations("file:" + filePath + "/"); // 图片存储路径
    }

}

3.获取访问路径

// HttpServletRequest 上传文件接口可获得
 private String getBaseUrl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
 // 图片的最终访问路径
 getBaseUrl(request) + /static/img/+图片名称.png

4.注意事项

权限限制需要将 /static/img/** 加入白名单 无需认证校验
例如 shiro 中需进行如下处理

@Configuration
public class ShiroConfig {

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        
        Map filterMap = new LinkedHashMap<>();
        filterMap.put("/static/img/**", "anon");
        shiroFilter.setFilterChainDefinitionMap(filterMap);

        return shiroFilter;
    }

你可能感兴趣的:(spring,boot,java,servlet)