How to show image from H2 database to Thymeleaf?

2019-08-10 07:47发布

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?

controller:

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

<form>
    <label>Avatar:</label>
    <input type="file" th:field="${usersss.Avatar}"/>
    <button type="submit">Submit</button>
</form>

shows:

<form>
    <label>Avatar:</label>
    <p>
        ?????????
    </p>
</form>

1条回答
SAY GOODBYE
2楼-- · 2019-08-10 08:04

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>

Hope this helps.

查看更多
登录 后发表回答