[英]How to display an blob image received from database using Spring Boot
親愛的社區,美好的一天。 嘗試通過 Base64 顯示從 MySQL 接收到的圖像時遇到問題。 圖像上傳並存儲在數據庫中沒有問題。
我的模型類:
@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}"/>
結果,我有這個:問題元素
我做錯了什么?
美好的願望。
您需要使用modelAndView.addObject("contentImage",base64Encoded );
添加到視圖中modelAndView.addObject("contentImage",base64Encoded );
並導入ModelAndView
並將您的方法更改為ModelAndView
並使用ModelAndView modelAndView = new ModelAndView("view");
實例化類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 返回的變量,如果需要,您可以添加更多值。
這是一個鏈接,可以通過一些示例幫助您解決此主題: ModelAndView
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.