Spring Boot 结合 Thymeleaf 开发电商网站无法加载图片问题求助
Spring Boot + Thymeleaf 商品图片加载异常修复方案
问题背景
使用 Spring Boot 和 Thymeleaf 开发运动品类电商网站时,商品列表首页和商品编辑页面均无法正常加载商品图片。触发错误的商品编辑页代码片段如下:
<div class="form-group"> <label for="">Image:</label> <input type="file" class="form-control" th:name="file" th:id="file"> <img class="mt-2" src="#" alt="" id="imgPreview1"> <br><br> <label for="">Current image:</label> <img style="width: 100px;" th:src="@{'media/'+${product.image}}"> </div>
已知图片存放在项目 src/main/resources/static/media 目录下,数据库读取文件名的逻辑已确认无异常,问题出在路径配置层面。
根因分析
当前使用的是相对路径写法@{'media/'+${product.image}},Thymeleaf 解析相对路径时会以当前页面的请求URL为基准拼接路径,例如编辑页URL为/product/edit/123时,最终生成的图片路径会是/product/edit/media/xxx.jpg,和静态资源实际所在的根路径/media/xxx.jpg不匹配,导致404错误。
修复步骤
- 修正Thymeleaf路径写法,在media前添加斜杠
/表示从项目根路径开始匹配:
<!-- 写法1:直接拼接路径 --> <img style="width: 100px;" th:src="@{'/media/'+${product.image}}"> <!-- 写法2:使用Thymeleaf路径变量写法,更规范 --> <img style="width: 100px;" th:src="@{/media/{filename}(filename=${product.image})}">
- 若修改后仍加载失败,依次做如下排查:
- 检查
application.properties/application.yml中是否有自定义静态资源映射配置,确认src/main/resources/static目录在静态资源扫描路径中,默认配置无需额外修改 - 若配置了项目上下文路径
server.servlet.context-path,无需手动拼接上下文,@{}语法会自动补全 - 直接在浏览器地址栏输入
http://localhost:你的端口/media/数据库中存储的图片文件名,验证静态资源本身是否可访问
内容的提问来源于stack exchange,提问作者Aabhas Amol
相关产品推荐
相关产品推荐

