【问题标题】:How to properly show profile picutre for user如何正确显示用户的个人资料图片
【发布时间】:2020-10-13 17:00:02
【问题描述】:

我的 Google-fu 似乎让我失望了,因为我找不到类似的问题或解决方案。 我想在用户个人资料页面中显示用户图像,但图像无法加载或仅消耗其他所有内容。

头像保存如下:

   @Lob
    @Basic(fetch = FetchType.EAGER)
    private byte[] profilePicture;

这是应该返回图像的控件。 HttpServeltResponse 是我发现的与此相关的东西,但我让图像占用了整个页面。

    @GetMapping("/profile")
    public String showporfile(Model model, Principal principal, HttpServletResponse response) throws IOException {
        acc = accountRepo.findByUsername(principal.getName());
        model.addAttribute("accountName", acc.getName());
        model.addAttribute("skills", acc.getSkills());
        model.addAttribute("accounts", acc);

        /*response.setContentType("image/jpg");

        InputStream is = new ByteArrayInputStream(acc.getProfilePicture());
        IOUtils.copy(is, response.getOutputStream());*/

        return "profile";
    }

这是我试图在其中显示图片的 HTML。目前我收到错误说明:由于被认为是客户端错误(例如,格式错误的请求语法、无效的请求消息帧或欺骗性请求路由),服务器无法或不会处理请求。似乎图像现在变为:http://localhost:8080/[B@1c535b01,我不知道为什么会这样。

        <div th:each="account : ${accounts}">
            <label th:text="${account.name}"></label>
            <div class="header_image clearfix">
                <img th:src="${account.profilePicture}"/>
            </div>
        </div>

感谢您的提前,我已经坚持了 3 天了。

编辑 图像存储到 h2 数据库并链接到用户。

【问题讨论】:

  • 我终于找到了一种解决方案,我刚问这个就觉得很傻。我将 HTML 替换为 现在图像显示正确,但我不确定这是正确的方法。来源:stackoverflow.com/questions/17772857/…

标签: java html spring spring-boot h2


【解决方案1】:

首先你要明白img标签的src属性是图片的URL,而不是图片本身。 鉴于您已经决定将图像存储在数据库中,您需要创建一个单独的端点来获取图像(例如“/profile/avatar”),您实际上以几乎与您相同的方式返回图像主体'重新尝试您的注释掉的代码。然后你会在 img src 中引用该端点。

顺便说一句,实际上有一种方法可以使用“数据”协议和 base64 编码(here's 一个例子)将图像嵌入到 html 中,但它只适用于小图像,我相信你会从学习中受益首先是通常的方式。

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多