Home > Net >  How to display an blob image received from database using Spring Boot
How to display an blob image received from database using Spring Boot

Time:11-06

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.

CodePudding user response:

You need to add to the view with modelAndView.addObject("contentImage",base64Encoded ); and also import ModelAndView and change your method to ModelAndView and instance the class ModelAndView with ModelAndView modelAndView = new ModelAndView("view"); like this:

import org.springframework.web.servlet.ModelAndView;
@GetMapping("/blog/{id}")

public ModelAndView 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 );

ModelAndView modelAndView = new ModelAndView("view");
modelAndView.addObject("contentImage",base64Encoded );
return modelAndView;

}

With this, you can call the variables returned from `modelAndView and you can add more values if you want.

Here is a link that can help you with this topic with some examples: ModelAndView

  • Related