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

9jyewag0  于 2023-01-13  发布在  Spring
关注(0)|答案(2)|浏览(276)

大家好,亲爱的社区。我在试图通过Base64显示从MySQL接收到的图像时遇到了一个问题。图像上传并存储在DB上没有问题。
我的模型类:

@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
我做错了什么?
祝你好运。

iibxawm4

iibxawm41#

您需要使用modelAndView.addObject("contentImage",base64Encoded );添加到视图中,还需要导入ModelAndView,将方法更改为ModelAndView,并使用ModelAndView modelAndView = new ModelAndView("view");示例化类ModelAndView,如下所示:

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返回的变量,如果需要,还可以添加更多的值。
以下链接提供了一些示例,可帮助您了解此主题:ModelAndView

j8ag8udp

j8ag8udp2#

你能分享一下ImageUpload代码吗?我在这里也遇到了同样的问题@Igor Gorski

相关问题