首页 > 解决方案 > 从 Thymeleaf src 标签中的 API 获取图像 URL

问题描述

我有一个 API,例如:

<IP>:<Port>/getProfilePic/{userName}

此 API 仅将 CDN URL 作为字符串返回,可以在其中找到该用户的图像。在 Thymeleaf 模板中,我正在做:

<img class="chat-message-author-pic" 
    th:src="@{'/getProfilePic/' + ${message.getUsername()}}" 
    width="15px" height="15px"/>

当然,响应被视为图像内容,而不是应加载图像的 URL。就像,对于其中一位用户,浏览器中的标签显示为:

<img class="chat-message-author-pic" width="15px" height="15px" 
    src="/getProfilePic/shubham">

如何使用 Thymeleaf 模板调用 API,获取应该作为src标签 URL 的字符串?这是否也适用于 Javascript 函数,div当我执行此操作时,它会将 HTML 附加到 a:

<img class="chat-message-author-pic" 
    th:src="@{/getProfilePic/' + username + '}" 
    width="15px" height="15px"/>' + ...

标签: spring-bootthymeleaf

解决方案


百里香不是去这里的路。相反,您应该:

  1. 在控制器中/getProfilePic/shubham,只需返回图像内容(使用 java 检索远程图像并将其传递)。

或者

  1. 将 url 放在不同的属性中。像这样的东西:

<img class="chat-message-author-pic" width="15px" height="15px" th:data-location="@{/getProfilePic/{user}(user=${message.username})}">

然后使用 JavaScript 填充src属性。

<script>
$(function() {
  $('.chat-message-author-pic').each(function (i, e) {
    $.get($(e).data('location'), function(data) {
      $(e).prop('src', data);
    }, 'text');
  });
});
</script>

推荐阅读