Good day dear community. I got a problem when trying to display received image from MySQL via Base64. Image uploaded and stored on DB without a problems.
My model class:
@Entity
public class PostModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column (name = "title")
private String title;
@Column (name = "preview")
private String preview;
@Column (name = "content")
private String content;
@Column (name = "views")
private int views;
@Lob
@Column (name = "image")
private byte[] image;
//Getters and setters
Controller:
@GetMapping("/blog/{id}")
public String showContent(@PathVariable(value = "id") long id, Model model) throws
UnsupportedEncodingException {
if (!postRepository.existsById(id)) {
return "redirect:/post_not_exist";
}
Optional<PostModel> post = postRepository.findById(id);
ArrayList<PostModel> content = new ArrayList<>();
post.ifPresent(content::add);
model.addAttribute("post", content);
byte[] encodeBase64 = Base64.getEncoder().encode(post.get().getImage());
String base64Encoded = new String(encodeBase64, "UTF-8");
model.addAttribute("contentImage", base64Encoded );
return "post_content";
}
And HTML tag:
<img src="data:image/jpg;base64,${contentImage}"/>
For result, I have this: The problem element
What I doing wrong?
Good wishes.