【问题标题】:Display an image with spring boot hibernate and JPA使用 Spring Boot Hibernate 和 JPA 显示图像
【发布时间】:2017-10-25 17:14:00
【问题描述】:

当我尝试从产品对象中添加 Base64 中的图像时,如下所示:

   <tbody>
      <tr th:each="product : ${products}">
        <td><img th:src="@{'data:image/png;base64,' + ${product.image}}" /></td>
        <td th:text="${product.name}"></td>
        <td th:text="${product.price}"></td>
        <td th:if="${product.state==true}" th:text="Activo" style="color:green;"></td>  
        <td th:if="${product.state==false}" th:text="Bloqueado" style="color:red;"></td>
        <td><a href="#" class="btn btn-info btn-xs" data-toggle="collapse" data-target="#collapse-form">Editar</a><a href="#" class="btn btn-danger btn-xs">Eliminar</a></td>
      </tr>
  </tbody>

{$product.image} 的值为 [B@776a398 但如果我输入 LOG.Info();这给我看based64 string。我该如何解决?

这是我的控制器:

@GetMapping("/admin/products") 
public ModelAndView index(){

    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    ModelAndView mvn = new ModelAndView();
    mvn.addObject("user",userServiceImpl.getOne(user.getUsername()));

    List<Product> products  = productServiceImpl.getAll();

    for(Product product : products)
    {
        byte[] encode = Base64.getEncoder().encode(product.getImage());
        product.setImage(encode);
        LOG.info(new String(encode));
    }

    mvn.addObject("products",products);
    mvn.setViewName(view);
    LOG.info("Se ha ingresado al controlador de productos");
    return mvn;

}

【问题讨论】:

标签: hibernate spring-mvc spring-boot spring-data-jpa thymeleaf


【解决方案1】:

当你获得产品图片的价值时:

 <img th:src="@{'data:image/png;base64,' + ${product.image}}" />

Thymeleaf 只是对你的 byte[] 进行toString(),在 java 中,默认 toString() 会获取一些不可读的值,这就是 thymeleaf 添加到 src 中的内容。

来自官方文档:

Object 类的 toString 方法返回一个字符串,该字符串由 对象是其实例的类的名称,at 符号 字符“@”和哈希的无符号十六进制表示 对象的代码。换句话说,这个方法返回一个字符串等于 值:

getClass().getName() + '@' + Integer.toHexString(hashCode())

因此,如果您需要获得与记录器中显示的相同的内容,您可以使用将其作为字符串返回的方法:

public class Product {

    //...
    public String getImageEncoded() {
         return new String(this.image);
    }

}

然后在thymeleaf中使用这个方法:

<img th:src="@{'data:image/png;base64,' + ${product.getImageEncoded()}}" />

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2020-03-16
    • 2017-07-09
    • 2020-02-04
    • 2016-03-08
    相关资源
    最近更新 更多