如何使用Thymeleaf向html页面添加图像?

问题描述 投票:0回答:1
java html spring-boot image thymeleaf
1个回答
0
投票

问题1:正确读取文件

如果您使用默认配置,那么您放入

src/main/resources
的任何内容都会复制到类路径中。因此,您的代码中不应引用
src/main/resources
,而应引用类路径本身。

所以理想情况下,您应该将控制器重写为:

// Get location from classpath
URI location = getClass().getClassLoader().getResource("static/logo.png").toURI();
// Get file
Path file = Paths.get(location);
// Read bytes
return new ByteArrayResource(Files.readAllBytes(file));

由于从文件中检索资源是一项常见任务,因此您实际上不必读取字节。 您可以使用

ByteArrayResource
而不是使用
FileSystemResource
:

// Get location from classpath
URI location = getClass().getClassLoader().getResource("static/logo.png").toURI();
// Get file
Path file = Paths.get(location);
return new FileSystemResource(file);

您甚至可以缩短这个时间,因为从类路径检索资源非常常见,因此有一个

ClasspathResource
类:

return new ClassPathResource("static/logo.png");

这还不是全部,通常情况下,您需要从类路径提供 Web 资源,因此在 Spring Boot 中,

classpath:static/
文件夹或
classpath:public/
文件夹中的所有内容都已在 Web 上提供。所以通常情况下,您的图片已经在
http://localhost:8080/logo.png
上可用。

所以通常你可以完全删除该控制器方法。


问题2:正确引用文件

这给我们带来了第二个问题。目前,您使用

@{/api/v1/logo}
@{src/main/resources/static/logo.png}
来引用您的图像。 Thymeleaf 将
@{path/to/file}
解释为上下文相关 URL,因此它唯一做的就是在上下文路径前面添加上下文路径(如果有的话),并期望该文件在
http://localhost:[serverport]/[contextpath]/path/to/file
处可用。

但正如我们之前所确定的,您的图像应该可以在

http://localhost:8080/logo.png
上找到,因此,您应该使用
@{/logo.png}
:

<img class="logo" th:src="@{/logo.png}" alt="Logo">

如果这不起作用,那么:

  • 您可能错误配置了构建工具,使其不在类路径中包含
    src/main/resources
  • 您可能已将 Spring Boot 配置为不自动提供
    classpath:static/
    classpath:public/
    中的任何内容。
© www.soinside.com 2019 - 2024. All rights reserved.