spring-boot - 从 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"/>' + ...
解决方案
百里香不是去这里的路。相反,您应该:
- 在控制器中
/getProfilePic/shubham
,只需返回图像内容(使用 java 检索远程图像并将其传递)。
或者
- 将 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>
推荐阅读
- angular - Angular 8:无法迭代我的帖子对象
- .net-core - 具有自定义名称的 Azure Pipeline Pack Nuget 包
- html - 在移动视图中 - 在容器和桌面视图中带有填充的图片不会发生
- mysql - 有没有办法通过 mysqldump 命令使用数据库 url?
- sql - 无法创建视图,但其他语句运行正常。每个视图或函数中的列名必须是唯一的
- arraylist - 为什么我的 arraylist 大小在适配器页面上等于 0?
- git - 通过詹金斯错误向 github 进行身份验证
- regex - 跟踪 Ruby 正则表达式中的分隔符更改
- c# - 带有 EmguCV 的 CUDA 中的 SEHException
- python - Flask - 服务器端的定期检查