【发布时间】:2020-11-10 08:49:14
【问题描述】:
我将头像图像存储在 Heroku 的 PGSQL 中,我曾经通过 API REST GET 控制器提供服务,一切都很好。我现在正在尝试通过 thymeleaf 在服务器域通过 API REST URL 提供服务,所以我为此准备了一个 MVC。一切正常,除了我不能使用服务器 URL 嵌入到我的前端应用程序的 HTML 标记中,它显示一个丢失的链接,我不明白,因为如果我在浏览器中打开链接本身它工作得很好并显示图像。
我正在尝试做的是类似于谷歌头像 HTML 的东西,我复制了谷歌 HTML 简单代码并在谷歌 HTML 作品中作为它使用,但不是我的......
谷歌示例: https://lh3.googleusercontent.com/a-/AOh14GgQ4X0_nQVH0NszR1-YGu90CIk40XSWT97uqW_V=s96-c
所以,两者都运行良好,但我只能在前端的 HTML IMG SRC 中使用谷歌,我的输出显示了一个 borken 链接。 :(
我的 HTML 模板:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${title}"></title>
<meta name="viewport" content="width=device-width, minimum-scale=0.1">
</head>
<body style="margin: 0px; background: #0e0e0e;">
<img style="-webkit-user-select: none;margin: auto;" th:if="${avatarData != null}" th:src="'data:image/jpeg;base64,' + ${avatarData}">
<img style="-webkit-user-select: none;margin: auto;" th:if="${avatarData == null}" th:src="@{${avatarURL}}">
</body>
</html>
还有我的控制器代码:
@GetMapping("/avatar")
public String getAvatar(@RequestParam(name="emailHash", required=false, defaultValue="") String hashEmail, Model model) {
User user = userRepository.findByHashEmail(hashEmail).orElseThrow(() -> new ResourceNotFoundException());
byte[] image = userService.getImageBlobByEmailHash(hashEmail, true, false);
model.addAttribute("title", "AVT-" + hashEmail);
if ( image != null ) {
model.addAttribute("avatarData", Base64.getEncoder().withoutPadding().encodeToString(image));
} else {
if ( user.getAvatar() != "" && user.getAvatar() != null ) {
model.addAttribute("avatarData", null);
model.addAttribute("avatarURL", user.getAvatar());
} else {
model.addAttribute("avatarURL", "/img/avatar-128.png");
}
}
return "avatar";
}
最后是我的前端,显示断开的链接:
<a href (click)="false" [routerLink]="'/social/user/'+user.hashEmail">
<img class="s-ava-alone-img" width="150" height="150" [src]="'https://chefscript.herokuapp.com/avatar?emailHash='+user.hashEmail">
</a>
【问题讨论】:
-
avatarURL是绝对 URL 吗?您可以尝试改用th:src="${avatarURL}"吗? -
我试过了。结果相同。并回答您的问题:是的,它是一个绝对 URL,它的工作原理如您在“我的输出”链接中所见。问题是我不能在前端将此输出用作 IMG SRC,所以在下一步中,我认为问题出在 HTML 端,但我不明白为什么。对不起,不是英语母语。
标签: html image heroku thymeleaf