'Is there a way to display an image from MySql database in thymeleaf and spring boot?
I created a MySQL database named: department. I can display all other columns from the database except the 'logo' which is in BLOB format. I can save image into 'logo' but I cannot display it in a thymeleaf table. Do I need a separate Controller for displaying image?
Here is my Thymeleaf to display image:
<td>
<img th:src="${tempDepartment.logo}" >
</td>
This is my entity:
@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;
This is my Controller:
//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";
}
I wish to display an image from the database but it is not showing.
Solution 1:[1]
Change your byte[] into a Base64 Image and in html file you need to try this..
< img th:src="*{'data:image/png;base64,'+image}" alt="" />
instead of
<img th:src="${tempDepartment.logo}" >
here your thymeleaf code will work if your controller have this parameter produces = MediaType.IMAGE_PNG_VALUE
for more details go through with this link
Solution 2:[2]
I solved this way:
Created a class with the method to convert byte array to string Here, the class is having instance method, You can use static method as well, with providing the complete path of the class
public class ImageUtil { public String getImgData(byte[] byteData) { return Base64.getMimeEncoder().encodeToString(byteData); } }In the controller, created an instance of ImageUtil, and add into model
model.addAttribute("imgUtil", new ImageUtil());In thymeleaf HTML file, used the below code
<img class='img-thumbnail' th:src="'data:image/jpeg;base64,' + ${imgUtil.getImgData(entity.imgData)}" />
Here, entity is an instance of the JPA entity or POJO
I invested a lot of time and efforts, and finally solved it. :)
Let me know, if you stuck somewhere
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vikrant Kashyap |
| Solution 2 | Rajiv Kumar |
