如何使用 Spring Boot 显示从数据库接收的 blob 图像

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

美好的一天,亲爱的社区。尝试通过 Base64 显示从 MySQL 接收到的图像时遇到问题。图片上传并存储在数据库上没有问题。

我的模型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

控制器:

    @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";
    }

和HTML标签:

   <img src="data:image/jpg;base64,${contentImage}"/>

对于结果,我有这个:The problem element

我做错了什么?

祝你好运。

您需要使用 modelAndView.addObject("contentImage",base64Encoded ); 添加到视图并导入 ModelAndView 并将您的方法更改为 ModelAndView 并实例化 class ModelAndView ModelAndView modelAndView = new ModelAndView("view"); 像这样:

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;

}

有了这个,您可以调用从 `modelAndView 返回的变量,如果需要,您可以添加更多值。

这里有一个 link 可以通过一些示例帮助您解决此主题:ModelAndView