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 it looks like this:
<div class="row">
<div class="col-sm-3 my-2 d-flex align-content-stretch flex-wrap" th:each="product : ${products}">
<div class="card">
<img class="card-img-top" th:src="${product.image}">
<div class="card-body">
<h5 class="card-title" th:text="${product.name}">Product name</h5>
<p class="card-text" th:text="${product.description}">Product summary</p>
<p class="card-text" th:text="${product.cost}">Product summary</p>
</div>
</div>
</div>
</div>
In controller I add all the products like this:
@GetMapping("/")
public String getHomePage(Model model) {
model.addAttribute("products", productRepository.findAll());
return "home";
}
And the product model is as shown:
@Entity
@Getter
public class Product extends BaseEntity {
private String name;
private String description;
@OneToOne
private Category category;
private double cost;
@Lob
private byte[] image;
public Product() {
super();
}
public Product(String name, String description, Category category, double cost, byte[] image) {
this();
this.name = name;
this.description = description;
this.category = category;
this.cost = cost;
this.image = image;
}
}
My problem is that I want to display multiple images at one time.
BTW, I know that the findAll
method is not a good choose, but It is only for testing proposes. Later I want to implement pagination, but first how to display, a byte array image?
image = Base64.getEncoder().encode(image);
and in view< img th:src="*{'data:image/png;base64,'+image}" alt="" />
– AgnusagoBase64
class there in no method encode which returnString
, but there isencodeToString
which works perfect. Thank You for help. – AblationBase64.getEncoder().encodeToString(byte[])
before setting it as Context Variable – Unquote