首页 > 解决方案 > 用于通过 Spring Boot 从数据库提供图像的 HTML

问题描述

我将头像图像存储在 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

我的输出: https ://chefscript.herokuapp.com/avatar?emailHash=7ad248c8b830100b95ae8fe57d6f07324b8d5c69872dcf4a5d280a993b8ab676

所以,两者都运作良好,但我只能在前端的 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>

标签: htmlimageherokuthymeleaf

解决方案


找到它。标头和响应类型的问题。我想通过 HTML/TEXT 使用头像图像,以便稍后在前端的 IMG SRC 中使用。糟糕的策略。我在 google 中看到 Content-Type 标头设置为 image/jpeg 并且 Content-Disposition 标头设置为内联。这样以后就可以使用了。


推荐阅读