So, i have a form that allows user to upload an image, which will be encoded with IOUtils.toByteArray and persisted to a database as a bytea. In a controller method i get this byte array and encode it to string:
@GetMapping("/{user_id}")
public String view(@PathVariable("user_id") Long user_id, Model model) {
User user = userService.getById(user_id);
model.addAttribute("user", user);
byte[] profilePictureBytes = user.getProfilePicture();
if (profilePictureBytes != null) {
String encodedImage = Base64.getEncoder().encodeToString(profilePictureBytes);
model.addAttribute("encodedImage", encodedImage);
}
return "user-page";
}
On a user-page html file i try to decode it like this:
<img th:src="*{'data:image/jpeg;base64,'+ ${encodedImage}}" alt="Profile Picture">
but it keeps throwing the same 2 exceptions:
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "'data:image/jpeg;base64,'+ ${encodedImage}" (template: "user-page" - line 27, col 6
org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
While debugging, the "encodedImage" variable prints out a correct string, so the problem must be within my Thymeleaf syntax.
Would be really grateful if someone could give me a hand with this one.
You can't nest expressions like you are doing -- *{ ... ${ ... } ... }
is not valid Thymeleaf syntax. See the Thymeleaf documentation on appending texts. In most cases, literal substitutions I think are most expressive.
<img th:src="|data:image/jpeg;base64,${encodedImage}|" alt="Profile Picture">
Or if you prefer regular String concatenation.
<img th:src="'data:image/jpeg;base64,'+ ${encodedImage}" alt="Profile Picture">
or
<img th:src="${'data:image/jpeg;base64,'+ encodedImage}" alt="Profile Picture">