【问题标题】:Spring MVC - Unable to load images in controllerSpring MVC - 无法在控制器中加载图像
【发布时间】:2021-11-11 09:05:11
【问题描述】:

更新:

我按照 M. Deinum 的建议使用 ClassPathResource 让它工作。 我还删除了我的 WebMvcConfig,但我不确定这是否与问题有关。

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImage() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("static/images/user-default.png");
        InputStream in = classPathResource.getInputStream();
        return IOUtils.toByteArray(in);
    }

我正在开发一个带有 Spring MVC 架构和 Spring Security 的 Spring Boot 项目。我无法确定我在哪里错误配置了我的 MVC 配置,我的 控制器 无法找到我指定的图像。

这是我提供图像的控制器:

@Controller
public class ImageController {
    @Autowired
    private ServletContext servletContext;
    
    @RequestMapping(value = "/image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImage() throws IOException {
        InputStream in = servletContext.getResourceAsStream("/images/user-default.png");
        return IOUtils.toByteArray(in);
    }
}

通过调试发现InputStream导致null。但是,我实际上能够通过 Thymeleaf 模板在我的浏览器上加载图像:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<!--omitted for brevity-->
<img th:src="@{/images/quiz-academic.png}"/> <!--This WORKS, image is VISIBLE in the browser-->
<!--omitted for brevity-->
</html>

或者通过直接路径访问它:

http://localhost:8080/images/user-default.png (This WORKS, image is VISIBLE in the browser)

我对为什么我的 控制器 无法获取图像感到困惑,而上述两种方法 (Thymeleaf,直接路径) 可以在没有任何问题。

这是我的 MVC 配置:

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/resources/", "classpath:/static/", "classpath:/images/");
    }
}

这是我的安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/error");
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/admin/**").access("hasAnyRole('ROLE_ADMIN')")
                .antMatchers("/user").access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
                .antMatchers("/css/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/image").permitAll()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated();
                /* login/logout configuration omitted for brevity */
    }
}

还有我的项目目录:

src/main/java/com/kjnts/springwebapp/config/WebSecurityConfig.java
src/main/java/com/kjnts/springwebapp/config/WebMvcConfig.java
src/main/java/com/kjnts/springwebapp/controller/ImageController.java
src/main/resources/static/images/user-default.png
src/main/resources/templates/user-profile.html

如果您想知道,我不使用 XML 进行 Spring 配置。

谢谢。

【问题讨论】:

  • 1.删除该图像 endpiint,2. 删除您的 WebMvcConfig(实际上禁用自动配置)。如果您确实需要该控制器,请不要使用ServletContext 加载文件(因为它会尝试从/WEB-INF 而不是类路径加载它。而是使用来自spring 的ClasspathResource,因为它需要来自类路径.
  • 谢谢。我已经让它与 ClassPathResource 一起正常工作。

标签: spring spring-boot spring-mvc


【解决方案1】:

我想我应该发布一个答案,以便我可以将其标记为已回答。


我按照 M. Deinum 的建议使用 ClassPathResource 让它工作。 我还删除了我的 WebMvcConfig,但我不确定这是否与问题有关。

@RequestMapping(value = "/image", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody byte[] getImage() throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("static/images/user-default.png");
        InputStream in = classPathResource.getInputStream();
        return IOUtils.toByteArray(in);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多