php小編西瓜在這篇文章中將向大家介紹如何使用Thymeleaf將圖像添加到HTML頁面。 Thymeleaf是一個受歡迎的伺服器端Java模板引擎,它允許我們在HTML頁面中使用動態(tài)資料。添加圖像是網(wǎng)頁設(shè)計中常見的需求,Thymeleaf提供了簡單而強(qiáng)大的功能來實現(xiàn)這一目標(biāo)。在接下來的內(nèi)容中,我們將學(xué)習(xí)如何使用Thymeleaf標(biāo)籤和表達(dá)式來引用和顯示圖像。無論你是初學(xué)者還是有經(jīng)驗的開發(fā)者,本文都將為你提供有用的指導(dǎo),讓你輕鬆地將圖像添加到HTML頁面中。
問題內(nèi)容
我的問題是我的 thymeleaf 區(qū)塊在 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:正確讀取檔案
如果您使用預(yù)設(shè)配置,則您放入 src/main/resources
的任何內(nèi)容都會複製到類別路徑中。因此,您不應(yīng)在程式碼中引用 src/main/resources
,而應(yīng)引用類別路徑本身。
如果您在本地運(yùn)行,它可能仍然可以工作,但是一旦您在其他地方運(yùn)行 jar 文件,它就會完全崩潰。
所以理想情況下,您應(yīng)該將控制器重寫為:
// 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));
由於從文件中檢索資源是一項常見任務(wù),因此您實際上不必讀取位元組。
您可以使用 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/
資料夾中的所有內(nèi)容都已經(jīng)在網(wǎng)路上。所以通常情況下,您的映像已經(jīng)可以在 http://localhost:8080/logo.png
上使用,而不需要您的控制器方法。
所以通常您可以完全刪除該控制器方法。
問題2:正確引用檔案
這給我們帶來了第二個問題。目前,您使用 @{/api/v1/logo}
或 @{src/main/resources/static/logo.png}
來引用您的圖片。
thymeleaf 將@{path/to/file}
解釋為上下文相關(guān)url,因此它唯一做的就是在上下文路徑前面添加上下文路徑(如果有的話)並期望該檔案在http ://localhost:[serverport ]/[contextpath]/path/to/file
。
但正如我們之前所確定的,您的映像應(yīng)該可以在http://localhost:8080/logo.png
上找到,因此,您應(yīng)該使用@{/logo. png}
:
<img class="logo" th:src="@{/logo.png}" alt="Logo">
如果這不起作用,那麼:
- 您可能錯誤配置了建置工具,未在類別路徑中包含
src/main/resources
。 - 您可能已將 spring boot 設(shè)定為不自動提供
classpath:static/
或classpath:public/
內(nèi)的任何內(nèi)容。
以上是如何使用 Thymeleaf 將圖像新增至 html 頁面?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)
