Shubham A.
Shubham A.

Reputation: 2534

Get Image URL from API in Thymeleaf src tag

I have an API like:

<IP>:<Port>/getProfilePic/{userName}

This API just returns a CDN URL as a String where image for this user can be found. In Thymeleaf template, I am doing:

<img class="chat-message-author-pic" 
    th:src="@{'/getProfilePic/' + ${message.getUsername()}}" 
    width="15px" height="15px"/>

Of course the response is being treated as the image content instead of a URL from where the image should be loaded. Like, for one of the user, the tag in browser appear as:

<img class="chat-message-author-pic" width="15px" height="15px" 
    src="/getProfilePic/shubham">

How can I use Thymeleaf templating so it call the API, get the String which should act as a URL for src tag? Will this work in Javascript function as well which appends HTML to a div when I do this:

<img class="chat-message-author-pic" 
    th:src="@{/getProfilePic/' + username + '}" 
    width="15px" height="15px"/>' + ...

Upvotes: 0

Views: 2020

Answers (1)

Metroids
Metroids

Reputation: 20477

Thymeleaf isn't the way to go here. Instead you should:

  1. In the controller for /getProfilePic/shubham, just return the image content (using java to retrieve the remote image and pass it along).

or

  1. Put the url in a different attribute. Something like this:

<img class="chat-message-author-pic" width="15px" height="15px" th:data-location="@{/getProfilePic/{user}(user=${message.username})}">

Then use JavaScript to populate the src attributes.

<script>
$(function() {
  $('.chat-message-author-pic').each(function (i, e) {
    $.get($(e).data('location'), function(data) {
      $(e).prop('src', data);
    }, 'text');
  });
});
</script>

Upvotes: 0

Related Questions