我创建了一个MySQL数据库,名为:department。我可以显示数据库中的所有其他列,但BLOB格式的“徽标”除外。我可以将图像保存到“徽标”中,但是无法在百里香叶表中显示。我需要一个单独的控制器来显示图像吗?
这是我的胸腺要显示图像:
<td>
<img th:src="${tempDepartment.logo}" >
</td>
这是我的实体:
@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@Column(name="dept_name")
private String deptName;
@Lob
@Column(name="logo")
private byte[] logo;
这是我的控制器:
//lists all departments
@GetMapping("/departments")
public String listDepartments(Model model) {
List<Department> departments = departmentService.findAll();
model.addAttribute("departments",departments);
return "/departments/list"; // Your current thymeleaf template
}
//adding a new department
@GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
Department theDepartment=new Department();
theModel.addAttribute("department",theDepartment);
return "/departments/department-form";
}
//saving a department
@PostMapping("/save")
public String saveDepartment(@ModelAttribute("department")
Department theDepartment) {
departmentService.save(theDepartment);
return "redirect:/home/departments";
}
我希望显示数据库中的图像,但未显示。
答案 0 :(得分:1)
将您的byte[]
更改为Base64
图像,并在html
文件中尝试此操作。
< img th:src="*{'data:image/png;base64,'+image}" alt="" />
代替
<img th:src="${tempDepartment.logo}" >
如果您的控制器具有此参数produces = MediaType.IMAGE_PNG_VALUE
有关更多详细信息,请访问this link
答案 1 :(得分:0)
我通过这种方式解决了
使用将字节数组转换为字符串的方法创建了一个类 这里,该类具有实例方法,您还可以使用静态方法,并提供该类的完整路径
public class ImageUtil {
public String getImgData(byte[] byteData) {
return Base64.getMimeEncoder().encodeToString(byteData);
}
}
在控制器中,创建ImageUtil的实例,并将其添加到模型中
model.addAttribute("imgUtil", new ImageUtil());
在百里香HTML文件中,使用下面的代码
<img class='img-thumbnail' th:src="'data:image/jpeg;base64,' + ${imgUtil.getImgData(entity.imgData)}" />
在这里,entity
是JPA实体或POJO的实例
我投入了大量时间和精力,终于解决了。 :)
如果您卡在某个地方,请告诉我