如何显示H2数据库中的图像到Thymeleaf?

时间:2015-11-21 03:14:47

标签: spring-mvc spring-boot thymeleaf

我正在使用H2数据库,百日咳视图进行春季启动。 我有一个表单上传图像保存到H2数据库(byte []图像), 在百里香,如何展示形象?有谁告诉我解决方案?

控制器:

@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>

1 个答案:

答案 0 :(得分:2)

虽然有很多不同的方法可以做到这一点,但这里有一些示例代码可供您使用:

@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()));
}

然后在你的百里香中:

<form>
<label >Avatar :</label>
 <p>
    <img class="picture" th:src="@{'/user/avatar/'+${userId}}" />
 </p>
</form>

希望这有帮助。