如何从 Thymeleaf 中的模型显示字节数组

slo*_*vic 6 spring-mvc thymeleaf

我想显示我的所有产品信息,但在显示产品图片时遇到问题。我从数据库获取我的产品,然后将它们添加到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>
Run Code Online (Sandbox Code Playgroud)

在控制器中,我添加了这样的所有产品:

@GetMapping("/")
public String getHomePage(Model model) {
    model.addAttribute("products", productRepository.findAll());
    return "home";
}
Run Code Online (Sandbox Code Playgroud)

产品型号如图:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我想一次显示多个图像。顺便说一句,我知道该findAll方法不是一个好的选择,但它仅用于测试建议。后来想实现分页,但是首先怎么显示,一个字节数组图片?

elk*_*tfi 7

我正在回答这个老问题,希望能帮助有相同需求的人。

为了使用字节显示图像,您必须创建一个具有显示图像作用的控制器操作:

@GetMapping("/product/image/{id}")
public void showProductImage(@PathVariable String id
                               HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg"); // Or whatever format you wanna use

Product product = productRepository.findById(id);

InputStream is = new ByteArrayInputStream(product.getImage());
IOUtils.copy(is, response.getOutputStream());
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以简单地显示您的图像:

<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/' + @{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> 
Run Code Online (Sandbox Code Playgroud)

PS:尽管您的图像属性使用了字节,但您最好使用包装器字节。这将让您管理没有图像的情况(空)

编辑:showProductImage 方法的最后一行是将 InputStream 复制到 OutputStream(查看IOUtils 文档以获取更多详细信息)