How to show image from H2 database to Thymeleaf?

浪尽此生 提交于 2020-01-05 23:59:37

问题


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:


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.



来源:https://stackoverflow.com/questions/33839309/how-to-show-image-from-h2-database-to-thymeleaf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!