【问题标题】:Get Image URL from API in Thymeleaf src tag从 Thymeleaf src 标签中的 API 获取图像 URL
【发布时间】:2018-05-22 08:16:37
【问题描述】:

我有一个类似的 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 函数,当我这样做时,它将 HTML 附加到 div

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

【问题讨论】:

  • 如果您使用 JavaScript 创建 DOM 元素并附加到 DIV,那么您必须使用常规 img src 属性,只要图像可访问,它就应该工作。

标签: spring-boot thymeleaf


【解决方案1】:

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

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

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

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

然后使用 JavaScript 填充 src 属性。

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

【讨论】:

  • 你的意思是我应该从 API 返回一个 File 对象吗?
  • 在带有上述图像标签的 Thymeleaf 中,我面临这个问题:imgur.com/a/QGTWAoO。我得到的例外是IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
  • 我不确定这个错误是什么意思......我用 thymeleaf 3/spring boot 测试了它,一切都对我有用。你的百里香叶设置正确吗?
  • 是的。我所有的页面都可以在 Thymeleaf 上正常工作,这是一个大项目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多