如何将 H2 数据库中的图像显示到 Thymeleaf? [英] How to show image from H2 database to Thymeleaf?
本文介绍了如何将 H2 数据库中的图像显示到 Thymeleaf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做 spring boot,使用 H2 数据库,thymeleaf 视图.我有一个表格可以上传图像以保存到 H2 数据库(字节 [] 图像),在百里香中,如何显示图像?有人告诉我解决办法吗?
I'm doing spring boot, using H2 database, thymeleaf view. I have a form to upload image to save into H2 database(byte[] image), In thymeleaf, how to show image? anyone tell me the solution?
控制器:
@RequestMapping(value = "user/new", method = RequestMethod.GET)
public String newBeans(Model model) {
model.addAttribute("usersss", new Beans());
return "userform";
}
@RequestMapping(value = "user", method = RequestMethod.POST)
public String saveUser(Beans beans) {
RepositoryUser.save(beans);
return "redirect:/users";
}
形式:
<form>
<label>Avatar:</label>
<input type="file" th:field="${usersss.Avatar}"/>
<button type="submit">Submit</button>
</form>
显示:
<form>
<label>Avatar:</label>
<p>
?????????
</p>
</form>
推荐答案
虽然有很多不同的方法可以做到这一点,但这里有一些示例代码,您可以使用:
Although there are many different ways to do this,here is some sample code which you can use for the same :
@RequestMapping(value = "/user/avatar/{userId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<InputStreamResource> downloadUserAvatarImage(@PathVariable Long userId) {
UserObject userAvatar = RepositoryUser.findUserAccountAvatarById(userId);//Could be a handle to a file stream as well,which could be incorporated accordingly
return ResponseEntity.ok()
.headers("Content-Disposition", "inline;filename=\""
+ userAvatar.getUserName() + "\"")
.contentLength(userAvatar.getImageBlob().getLength())
.contentType(MediaType.parseMediaType(userAvatar.getImageBlob().getContentType()))
.body(new InputStreamResource(userAvatar.getImageBlob().getBinaryStream()));
}
然后在你的百里香叶中:
And then in your thymeleaf :
<form>
<label >Avatar :</label>
<p>
<img class="picture" th:src="@{'/user/avatar/'+${userId}}" />
</p>
</form>
希望这会有所帮助.
这篇关于如何将 H2 数据库中的图像显示到 Thymeleaf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文