0

It seems that my Google-fu has failed me since I can't find similiar problems or solutions. I want to show users image in the users profile page, but the image eather does not load or just consumes everything else.

The profile picture is save as such:

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

This the controlle which should return the image. The HttpServeltResponse is something I found related to this, but I made the image consume the whole page.

    @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";
    }

And this is my HTML in which I have tried to get the picture to show. At the moment I get error stating: The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing). It seems that the image is now going as: http://localhost:8080/[B@1c535b01 and I don't know why that is.

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

Thank you for advance I have been stuck with this for 3 days now.

EDIT the image is stored to h2 database and linked to user as seen up.

Jupi
  • 35
  • 4
  • I found a kind of solution finally, feels silly since I just asked this. I replaced the HTML to And now the image shows correctly, but I am not sure this is the way proper way of doing this. source: https://stackoverflow.com/questions/17772857/how-to-display-jpg-from-db-web-page – Jupi Oct 13 '20 at 09:00

1 Answers1

1

The first thing you have to understand is that src attribute of the img tag is the URL of the image, and not the image itself. Given you've already decided to store the image in a database, you'll need to create a separate endpoint to get the image (e.g. "/profile/avatar") where you actually return the image body pretty much the same way you're trying in your commented-out code. And then you would refer to that endpoint in your img src.

BTW, Actually there is a way to embed an image into html using "data" protocol and base64 encoding (here's one example of it), but it's only suitable for tiny images, and I believe you would benefit from learning the usual way first.

rnov
  • 435
  • 2
  • 3