[Spring] 타임리프로 이미지 넣기

2023. 12. 24. 16:17Spring

다음과 같이 src에 ${content.image}로 넣어야한다.

<img th:if="${content.image != null}" th:src="@{'data:image/jpeg;base64,' 
+ ${content.image}}" width="100" height="100" alt="Image"/>

아래와 같이 자바코드를 사용해서 하면 안된다. 아마 타임리프 문법이 다르기 때문일 것이다.

<img th:if="${content.image != null}" th:src="@{'data:image/jpeg;base64,' + 
T(java.util.Base64).getEncoder().encodeToString(content.image)}" width="500" height="500" alt="Image"/>

 

또한 주의할 점은 image는 다음과 같이 String이어야 한다. byte[]이면 안된다.

Base64.getEncoder().encodeToString(form.getImage().getBytes());

 

그래서 한가지 우려되는게 Content Entity를 설계할 때 String으로 바꾸어야하는데 이게 맞는가 싶다. byte[]로 두는게 더 범용성이 크지 않을까 생각한다. 따라서 이 방법은 지금 생각으로는 좋지 못하다고 생각한다.

 

Reference


https://stackoverflow.com/questions/48235379/how-to-display-byte-array-from-a-model-in-thymeleaf

 

How to display byte array from a model in Thymeleaf

I want to display all my products info, but I have problem with showing a product image. I get my products from DB and then I add them to Model, but don't know why only image don't display. In HTML...

stackoverflow.com