弹簧RestTemplate:交两者的图像,并在同一时间的对象 [英] Spring RestTemplate: post both an image and an object at the same time

查看:468
本文介绍了弹簧RestTemplate:交两者的图像,并在同一时间的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户可以发布的东西,食物中的照片和食物的东西是要我的服务器什么职位。

例如,让说,有人看到好吃的东西,捕捉它的图片,然后写道:好吃!画面下方。照片被发送到服务器,并且消息美味!包括用户姓名,日期,地点等被称为后来使用一个API调用我的服务器的对象发送。

我写了下面的code在我的Andr​​oid端:

 最后字符串的URL = Constants.POST_PICS;
    RestTemplate restTemplate = RestClientConfig.getRestTemplate(背景下,真正的);
    //添加StringHttpMessageConverter,formHttpMessageConverter和MappingJackson2HttpMessageConverter到restTemplate
    。restTemplate.getMessageConverters()增加(新StringHttpMessageConverter());
    FormHttpMessageConverter formHttpMessageConverter =新FormHttpMessageConverter();
    。restTemplate.getMessageConverters()加(formHttpMessageConverter);
    。restTemplate.getMessageConverters()增加(新MappingJackson2HttpMessageConverter());
    //把两个对象放入地图
    MultiValueMap<弦乐,对象>地图=新LinkedMultiValueMap<弦乐,对象>();
    map.add(形象,新的FileSystemResource(文件));
    map.add(后,后);
    HttpHeaders imageHeaders =新HttpHeaders();
    //设定内容类型为多作为图像是一个多档
    imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity< MultiValueMap<弦乐,对象>> imageEntity =新HttpEntity< MultiValueMap<弦乐,对象>>(地图,imageHeaders);
    ResponseEntity<邮政和GT;响应= restTemplate.exchange(URL,HttpMethod.POST,imageEntity,Post.class);
    返回response.getBody();

这是在春天侧code:

  @RequestMapping(值=/ uploadpostpic,方法= RequestMethod.POST)
公共邮政uploadPostWithPic(@RequestParam(图像)MultipartFile SRCFILE,
                                  @RequestParam(后)发布后){
    返回serviceGateway.uploadPostWithPic(SRCFILE,后);
}

我得到一个错误:


  

要求网络执行过程中出现的异常:无法
  写请求:发现请求类型没有合适的HttpMessageConverter
  [Model.Post]


  
  

org.springframework.http.converter.HttpMessageNotWritableException:
  无法写请求:发现没有合适的HttpMessageConverter
  请求类型[Model.Post]


我怀疑它是与内容类型被设定为MULTIPART_FORM_DATA做,但我需要将其设置为这个,因为我需要的图片上来传输到服务器。

它甚至有可能传送一个多文件和另一个目的上游同时使用restTemplate

编辑:

我已经看过这些帖子:

<一个href=\"http://stackoverflow.com/questions/29184215/resttemplate-form-multipart-image-json-in-post\">Resttemplate表格/多部分:图片+ JSON的POST

<一个href=\"http://stackoverflow.com/questions/4118670/sending-multipart-file-as-post-parameters-with-resttemplate-requests\">Sending分段文件与RestTemplate POST请求的参数

根据他们的指导这个code

和尝试:

 最后字符串的URL = Constants.POST_PIC;
    RestTemplate restTemplate =新RestTemplate();
    。restTemplate.getMessageConverters()增加(新StringHttpMessageConverter());
    。restTemplate.getMessageConverters()增加(新ByteArrayHttpMessageConverter());
    。restTemplate.getMessageConverters()增加(新MappingJackson2HttpMessageConverter());
    。restTemplate.getMessageConverters()增加(新ResourceHttpMessageConverter());    FormHttpMessageConverter formHttpMessageConverter =新FormHttpMessageConverter();
    formHttpMessageConverter.addPartConverter(新MappingJackson2HttpMessageConverter());
    formHttpMessageConverter.addPartConverter(新ResourceHttpMessageConverter()); //这是希望驱动编程
    formHttpMessageConverter.addPartConverter(新ByteArrayHttpMessageConverter());    。restTemplate.getMessageConverters()加(formHttpMessageConverter);    MultiValueMap&LT;弦乐,对象&gt; multipartRequest =新LinkedMultiValueMap&LT;&GT;();    字节[] = BFILE新的字节[(INT)imageFile.length()];
    的FileInputStream的FileInputStream;    //文件转换成字节数组
    的FileInputStream =新的FileInputStream(镜像文件);
    fileInputStream.read(BFILE);
    fileInputStream.close();    使用ByteArrayResource字节=新使用ByteArrayResource(BFILE){
        @覆盖
        公共字符串用GetFileName(){
            返回file.jpg
        }
    };    //将multipartRequest的后部分
    HttpHeaders xHeader =新HttpHeaders();
    xHeader.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity&LT;邮政和GT; xPart =新HttpEntity&LT;&GT;(邮局,xHeader);
    multipartRequest.add(后,xPart);    在multipartRequest的//一部分图片
    HttpHeaders pictureHeader =新HttpHeaders();
    pictureHeader.setContentType(MediaType.IMAGE_JPEG);
    HttpEntity&LT;使用ByteArrayResource&GT; picturePart =新HttpEntity&LT;&GT;(字节,pictureHeader);
    multipartRequest.add(SRCFILE,picturePart);    //用于向服务器添加两个职位和图片部分一httpentity
    HttpHeaders头=新HttpHeaders();
    header.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity&LT; MultiValueMap&LT;弦乐,对象&gt;&GT; requestEntity =新HttpEntity(multipartRequest,头);
    返回restTemplate.postForObject(URL,requestEntity,Post.class);

在另一侧,后= NULL,我不知道为什么它为null。

这是所有我想在服务器端做的:

 公开发表uploadPostPic(MultipartFile SRCFILE,后后){
    帖子savedPost = repo.save(岗位);
 }

我保存到我的仓库和错误是:

  java.lang.IllegalArgumentException异常:实体不能为空!


解决方案

我用这个做类似的事情:

  HttpHeaders标题=新HttpHeaders();
  headers.add(接受,应用/ JSON);
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  MultiValueMap&LT;弦乐,对象&gt;地图=新LinkedMultiValueMap&LT;弦乐,对象&gt;();
  map.add(形象,新的FileSystemResource(文件));
  map.add(后,后);
  HttpEntity&LT; MultiValueMap&LT;弦乐,对象&gt;&GT; requestEntity =新HttpEntity&LT; MultiValueMap&LT;弦乐,对象&gt;&GT;(地图,头);
  RestTemplate restTemplate = RestClientConfig.getRestTemplate(背景下,真正的);
  。restTemplate.getMessageConverters()增加(新FormHttpMessageConverter());
  ResponseEntity&LT;邮政和GT;响应= restTemplate.postForObject(URL,requestEntity,Post.class);

My users can post a photo of a food stuff and a post of what the food stuff is about to my server.

For example, let say, someone sees something delicious, snaps a picture of it and then writes "Tasty!" underneath the picture. The photo is sent to the server, and the message "Tasty!" including the users name, date, location etc is sent in an object called "Post" to my server using one api call.

I have written the following code on my android side:

    final String url = Constants.POST_PICS;
    RestTemplate restTemplate = RestClientConfig.getRestTemplate(context, true);
    //adding StringHttpMessageConverter, formHttpMessageConverter and MappingJackson2HttpMessageConverter to restTemplate
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    restTemplate.getMessageConverters().add(formHttpMessageConverter);
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    //putting both objects into a map
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
    map.add("image", new FileSystemResource(file));
    map.add("post", post);
    HttpHeaders imageHeaders = new HttpHeaders();
    //setting content type to multipart as the image is a multipart file
    imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<MultiValueMap<String, Object>>(map, imageHeaders);
    ResponseEntity<Post> response = restTemplate.exchange(url, HttpMethod.POST, imageEntity, Post.class);
    return response.getBody();

This is the code on the Spring side:

        @RequestMapping(value = "/uploadpostpic", method = RequestMethod.POST)
public Post uploadPostWithPic(@RequestParam("image") MultipartFile srcFile,
                                  @RequestParam("post") Post post) {
    return serviceGateway.uploadPostWithPic(srcFile, post);
}

I'm getting an error:

An exception occurred during request network execution :Could not write request: no suitable HttpMessageConverter found for request type [Model.Post]

org.springframework.http.converter.HttpMessageNotWritableException: Could not write request: no suitable HttpMessageConverter found for request type [Model.Post]

I suspect it is to do with the content-type being set to MULTIPART_FORM_DATA but I need it set to this as I need to transfer the picture up to the server.

Is it even possible to transfer a multipart file and another object upstream using restTemplate at the same time?

EDIT:

I have looked at these posts:

Resttemplate form/multipart: image + JSON in POST

Sending Multipart File as POST parameters with RestTemplate requests

And tried according to their guidance this code:

    final String url = Constants.POST_PIC;
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
    restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());

    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.addPartConverter(new MappingJackson2HttpMessageConverter());
    formHttpMessageConverter.addPartConverter(new ResourceHttpMessageConverter()); // This is hope driven programming
    formHttpMessageConverter.addPartConverter(new ByteArrayHttpMessageConverter());

    restTemplate.getMessageConverters().add(formHttpMessageConverter);

    MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();

    byte[] bFile = new byte[(int) imageFile.length()];
    FileInputStream fileInputStream;

    //convert file into array of bytes
    fileInputStream = new FileInputStream(imageFile);
    fileInputStream.read(bFile);
    fileInputStream.close();

    ByteArrayResource bytes = new ByteArrayResource(bFile) {
        @Override
        public String getFilename() {
            return "file.jpg";
        }
    };

    //post portion of the multipartRequest
    HttpHeaders xHeader = new HttpHeaders();
    xHeader.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Post> xPart = new HttpEntity<>(post, xHeader);
    multipartRequest.add("post", xPart);

    //picture portion of the multipartRequest
    HttpHeaders pictureHeader = new HttpHeaders();
    pictureHeader.setContentType(MediaType.IMAGE_JPEG);
    HttpEntity<ByteArrayResource> picturePart = new HttpEntity<>(bytes, pictureHeader);
    multipartRequest.add("srcFile", picturePart);

    //adding both the post and picture portion to one httpentity for transmitting to server
    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.MULTIPART_FORM_DATA); 
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity(multipartRequest, header);
    return restTemplate.postForObject(url, requestEntity, Post.class);

On the other side, the post = null and I'm not sure why it is null.

This is all I'm trying to do on the server side:

public Post uploadPostPic(MultipartFile srcFile, Post post) {
    Post savedPost = repo.save(post);
 }

I'm saving it into my repository and the error is :

java.lang.IllegalArgumentException: Entity must not be null!

解决方案

I made something similar using this:

  HttpHeaders headers = new HttpHeaders();
  headers.add("Accept","application/json");     
  headers.setContentType(MediaType.MULTIPART_FORM_DATA);
  MultiValueMap<String, Object> map =  new LinkedMultiValueMap<String, Object>();
  map.add("image", new FileSystemResource(file));
  map.add("post", post);
  HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
  RestTemplate restTemplate = RestClientConfig.getRestTemplate(context, true);
  restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
  ResponseEntity<Post> response = restTemplate.postForObject(url, requestEntity, Post.class);

这篇关于弹簧RestTemplate:交两者的图像,并在同一时间的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆