英文:
Getting exceptions while trying to display encoded images with Thymeleaf (Java, Spring Boot)
问题
在用户页面的HTML文件中,您可以尝试以下方式解码图像:
<img th:src="'data:image/jpeg;base64,' + ${encodedImage}" alt="Profile Picture">
这应该解决您遇到的异常问题。
英文:
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.
答案1
得分: 1
你不能像你现在这样嵌套表达式 -- *{ ... ${ ... } ... }
不是有效的Thymeleaf语法。请查看Thymeleaf文档中关于追加文本的部分。在大多数情况下,我认为直接的替代方式更具表现力。
<img th:src="|data:image/jpeg;base64,${encodedImage}|" alt="Profile Picture">
或者如果你更喜欢常规的字符串连接方式。
<img th:src="'data:image/jpeg;base64,'+ ${encodedImage}" alt="Profile Picture">
或者
<img th:src="${'data:image/jpeg;base64,'+ encodedImage}" alt="Profile Picture">
英文:
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">
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论