如何在休息服务中使用带有@RequestBody的MULTIPART_FORM_DATA发送帖子

时间:2018-01-03 11:08:06

标签: rest spring-boot

我想将@RequestBody作为发布请求发送到restful service.In @RequestBody我有idtitleaboutMe和{{1}我设置image file但是当我检查休息时,我会收到错误消息 406不接受。我该如何解决?

我的控制器:

produces = MediaType.MULTIPART_FORM_DATA_VALUE

和实体

@RequestMapping(value = "aboutMe", method = RequestMethod.POST, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String saveAboutMe(@RequestBody Author author) {
        authorService.saveAboutMe(author);
        return "saved";
    }

我从休息error获得的截图

1 个答案:

答案 0 :(得分:0)

你无法传递@RequestBody和Blob对象,图像应该是MultipartFile对象。所以对于工作代码:

1)将SessionFactory注入控制器类或要将Mulitpart转换为Blob对象的任何类

@Autowired
private SessionFactory sessionFactory;

2)Controller类的更改:

@RequestMapping(value = "aboutMe", method = RequestMethod.POST)
public String saveAboutMe(Author author,@RequestPart("image") MultipartFile imageFile) {
    //Convert Multipart file into BLOB
    try {
        Blob image = Hibernate.getLobCreator(sessionFactory.getCurrentSession()).createBlob(authorImage.getInputStream(),authorImage.getSize());
        author.setImage(image);
    } catch (HibernateException | IOException  exception) {
        log.error(exception.getMessage(),exception);
    }

    authorService.saveAboutMe(author);
    return "saved";
}