我无法在 thymleaf 中显示字节图像,它来自数据库作为 blob,然后转换为 byte[],当我从数据库中获取图像时,查询已成功实现,但它无法在 thymleaf 中显示,下面是代码
DaoImpl 代码 daoimpl 中用于从数据库中检索图像的函数
在这个函数中,通过使用查询从数据库中选择 blob,然后将 blob 转换为字节,并将字节直接发送到 Controller
@Override
public byte[] stockProductMenData()
{
Session session = getSession();
byte[] Imagebytes = null;
Query query = session.createQuery("select sp.stockProductPic "
+ "from StockType st,StockProduct sp"
+ " where st.stockTypeId=sp.stockTypeId and st.stockTypeName = :stockTypeName");
query.setParameter("stockTypeName","MEN");
List<Blob> list = query.list();
System.out.println("List size :"+list.size());
Iterator<Blob> itr = list.iterator();
while(itr.hasNext())
{
Blob blob = itr.next();
try {
Imagebytes =blob.getBytes(1,(int) blob.length());
System.out.println("dddddd"+Imagebytes);
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("eeeeeee"+e);
}
}
控制者 在 Controller 中,我们收到字节数组并以 base64 编码并发送到 thymleaf 页面
@RequestMapping(value = "/mens" , method = RequestMethod.GET)
public ModelAndView custMen()
{
ModelAndView modelAndView =new ModelAndView();
byte[] picContent = customerDao.stockProductMenData();
byte[] encoded = Base64.getEncoder().encode(picContent);
System.out.println("ssssssssss"+picContent);
modelAndView.addObject("pic",encoded);
modelAndView.setViewName("mens");
return modelAndView;
}
带有 thymleaf 的前端 在这里我们收到图片的对象并使用 thymleaf 显示但图片不显示
<a href="mens_single.html">
<div class="cbp-pgitem a3ls">
<div class="cbp-pgitem-flip">
<img alt="Image" th:field="${pic}" width="250" height="250"/>
</div>
</div>
最佳答案
假设您发送了一个 byte[] 以存储在您的数据库中....
将 Base64 编码字符串添加到您的模型映射:
//I'm using a model here but the concept is the same model.addAttribute("pic",Base64.getEncoder.encodeToString(*your_blob*));
在你的 thymeleaf 片段中:
<img th:src="${pic} == null ? _ : @{'data:image/png;base64,'+${pic}}">
Thymeleaf 的模板引擎将有助于将您的 Base64 字符串转换为图像。
关于java - 无法在 thymeleaf 中显示 byte[] 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221468/