我想显示我所有的产品信息,但我在显示产品图片时遇到问题。我从DB中获取产品,然后将它们添加到Model
中,但不知道为什么只有图片不显示。在HTML中,它看起来像这样:
<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>
在控制器中,我添加了所有这样的产品:
@GetMapping("/")
public String getHomePage(Model model) {
model.addAttribute("products", productRepository.findAll());
return "home";
}
产品型号如图所示:
@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;
}
}
我的问题是我想一次显示多个图像。顺便说一句,我知道findAll
方法不是一个好的选择,但它只是为了测试建议。稍后我想实现分页,但首先如何显示,一个字节数组的图像?
3条答案
按热度按时间0x6upsns1#
我在回答这个老问题,希望能帮助有同样需要的人。
为了使用字节显示图像,您必须创建一个具有显示图像角色的控制器操作:
因此,您可以简单地显示图像:
PS:你最好使用 Package 器Byte,尽管你的图像属性是byte。这将让你管理没有图像的情况(空)
Edit:showProductImage方法的最后一行是将InputStream复制到OutputStream(查看IOUtils文档以了解更多详细信息)
new9mtju2#
在使用Sping Boot 时遇到了同样的问题,我不相信使用HttpServletResponse在单独的请求中获取图像,因为我们已经检索了模型属性中包含的图像字节数组,我想知道:如何从字节数组本身加载图像?
通过将图像字节数组转换为base64字符串并将其传递给JavaScript以填充图像预览元素,找到了解决方案:
在Java中
添加一个额外的String属性,表示图像的base64编码值:
从数据库中获取对象后,增加一个额外的步骤,从图像字节数组进行base64转换,如下所示:
在JSP/HTML中
添加一个包含图像的base64字符串的额外隐藏字段
在JavaScript中
通过隐藏字段中的base64值设置图像内容
此外,还可以将图像存储为Base64字符串并摆脱自定义转换阶段...
yptwkmov3#
这就是我的工作,转换图像到Base64,并注入到Thymeleaf使用一个Map,例如
使用以下方式显示图像:
<img th:src="${'data:image/jpeg;charset=utf-8;base64,' + images.get(product.id)}" alt="">