首頁 > Java > 主體

如何使用 Thymeleaf 將圖像新增至 html 頁面?

PHPz
發布: 2024-02-09 17:30:12
轉載
1291 人瀏覽過

php小編西瓜在這篇文章中將向大家介紹如何使用Thymeleaf將圖像添加到HTML頁面。 Thymeleaf是一個受歡迎的伺服器端Java模板引擎,它允許我們在HTML頁面中使用動態資料。添加圖像是網頁設計中常見的需求,Thymeleaf提供了簡單而強大的功能來實現這一目標。在接下來的內容中,我們將學習如何使用Thymeleaf標籤和表達式來引用和顯示圖像。無論你是初學者還是有經驗的開發者,本文都將為你提供有用的指導,讓你輕鬆地將圖像添加到HTML頁面中。

問題內容

我的問題是我的 thymeleaf 區塊在 html 頁面上不顯示圖片和捷徑圖示

我嘗試使用檔案路徑:

<img class="logo" th:src="@{src/main/resources/static/logo.png}" alt="logo">
登入後複製

並且也嘗試使用rest api:

<img class="logo" th:src="@{/api/v1/logo}" alt="logo">
登入後複製

有控制器:

@RestController
@RequestMapping("/api/v1/logo")
public class LogoController {

    @GetMapping(produces = MediaType.IMAGE_JPEG_VALUE)
    public Resource getLogo() throws IOException {
        return new ByteArrayResource(Files.toByteArray(new File("src/main/resources/static/logo.png")));
    }
}
登入後複製

而且我總是得到 alt 而不是圖像...

解決方法

問題1:正確讀取檔案

如果您使用預設配置,則您放入 src/main/resources 的任何內容都會複製到類別路徑中。因此,您不應在程式碼中引用 src/main/resources,而應引用類別路徑本身。

如果您在本地運行,它可能仍然可以工作,但是一旦您在其他地方運行 jar 文件,它就會完全崩潰。

所以理想情況下,您應該將控制器重寫為:

// 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));
登入後複製

由於從文件中檢索資源是一項常見任務,因此您實際上不必讀取位元組。 您可以使用 filesystemresource 來取代 bytearrayresource

// 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/資料夾中的所有內容都已經在網路上。所以通常情況下,您的映像已經可以在 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/ 內的任何內容。

以上是如何使用 Thymeleaf 將圖像新增至 html 頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!