前端访问图片配置

在日常开发中,前端需要访问一个图片,后端需要做的一些配置,记录一下如何操作。

项目使用的是 SpringSecurity 安全框架。

首先需要配置静态资源的映射,使得特定的路由前缀可以访问静态资源。

需要实现 WebMvcConfigurer接口,它是 Spring MVC 提供的配置接口,允许我们自定义 MVC 配置,包括静态资源的映射。

我们重写了 WebMvcConfigurer 接口中的 addResourceHandlers 方法,用于配置静态资源的映射关系。 ResourceHandlerRegistry 对象用于注册静态资源的处理器。

实现

通过 addResourceHandler 方法,映射一个 profile 后面的任意路由,跳转到 D:upload/ 下,也就是说,将 profile替换了实际的路径。

java 复制代码
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        registry.addResourceHandler("/profile/**")
                .addResourceLocations("file:" + "/D:upload/");
    }

去除 Security 认证

静态资源是不需要认证的哈

在 Spring Security 中用于配置 Security 的认证情况,我们设置指定路径不进行认证。

java 复制代码
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.authorizeRequests(expressionInterceptUrlRegistry ->
            expressionInterceptUrlRegistry.antMatchers("/login", "/captchaImage", "/register").permitAll()
                    // 下面是追加对资源的释放,并设置get请求
                    .antMatchers(HttpMethod.GET, "/profile/**").permitAll()
                    // 其他请求需要认证
                    .anyRequest().authenticated())
            
    return httpSecurity.build();
}

这样就可以通过路径访问了。

前端通过路径访问即可

html 复制代码
<img src="http://localhost:8080/profile/avatar.jpg" alt="User Avatar">
相关推荐
卷无止境4 分钟前
FastAPI生产环境密钥管理全解析,从一个.env文件说起
后端·python·fastapi
祀爱8 分钟前
C# MQTT 连接服务
后端·c#·.net
恋猫de小郭8 分钟前
Firebase 如何让全球 Android 和 Flutter 开发者集体 Build Fail
android·前端·flutter
墨白曦煜9 分钟前
智能体架构范式总结(React、Plan-And-Solve、Reflection)
前端·react.js·前端框架
卷无止境9 分钟前
SigV4与HTTPS,两套完全不同维度的安全机制
后端·python·fastapi
青石路11 分钟前
好好的OceanBase官方驱动你不用,非要用第三方驱动,ArrayIndexOutOfBoundsException了吧
java·后端
qq_4260039612 分钟前
多语言新增语种全量测试策略的测试范围
前端·javascript·python·自动化
frjc23 分钟前
Node.js 与 npm 极简安装教程
前端·npm·node.js
IMPYLH24 分钟前
HTML 的 <main> 元素
前端·html
深念Y26 分钟前
微服务抽取路线图:从胖单体到 ARM 集群
前端·arm开发·数据库·后端·微服务·云原生·架构