Spring RestTemplate:同时发布图像和对象

时间:2015-12-05 18:47:17

标签: android spring spring-boot resttemplate

我的用户可以在我的服务器上发布食物照片和食物内容的帖子。

例如,假设有人看到美味的东西,拍下它的照片,然后写下“好吃的!”#34;在图片下面。照片被发送到服务器,消息"美味!"包括用户名,日期,位置等在一个名为" Post"的对象中发送。使用一个api调用到我的服务器。

我在android端编写了以下代码:

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

这是Spring方面的代码:

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

我收到错误:

  

请求网络执行期间发生异常:无法执行   写请求:没有为请求类型找到合适的HttpMessageConverter   [Model.Post]

     

org.springframework.http.converter.HttpMessageNotWritableException:   无法写入请求:找不到合适的HttpMessageConverter   请求类型[Model.Post]

我怀疑它与设置为MULTIPART_FORM_DATA的内容类型有关,但我需要将其设置为此,因为我需要将图片传输到服务器。

是否可以同时使用restTemplate传输多部分文件和另一个上游对象?

编辑:

我看过这些帖子:

Resttemplate form/multipart: image + JSON in POST

Sending Multipart File as POST parameters with RestTemplate requests

并根据他们的指导尝试了这段代码:

    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);

另一方面,post = null,我不知道为什么它为null。

这就是我在服务器端试图做的所有事情:

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

我将其保存到我的存储库中,错误是:

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

5 个答案:

答案 0 :(得分:1)

尝试这样的事情: 在这里发送jsonString,然后使用objectwriter将其转换为对象。让我知道您是否需要更多解释。

@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
    public @ResponseBody
    String uploadMultipleFileHandler(@RequestParam("name") String[] names,
            @RequestParam("file") MultipartFile[] files) {

        if (files.length != names.length)
            return "Mandatory information missing";

        String message = "";
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String name = names[i];
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());

                message = message + "You successfully uploaded file=" + name
                        + "<br />";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        }
        return message;
    }
}

<强>编辑:

最终,我不得不使用jsonString来解决我的问题。这不是理想的,因为网址最终变得很长,但这是解决我问题的最快方法:

请查看mykong关于如何将对象转换为jsonString并将其重新转换回对象的建议:

ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(obj);

//JSON from String to Object
Staff obj = mapper.readValue(jsonInString, Staff.class);

http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

答案 1 :(得分:0)

我没有为你的Post类看到一个注册的HttpMessageConverter。您可能必须为MultiValueMap注册一个HttpMessageConverter。

答案 2 :(得分:0)

oookay,几周前我遇到了同样的问题。首先要明确multipart/form-data内容类型的含义:

  

“multipart / form-data”消息包含一系列部分   代表一个成功的控制。

     

成功的控制对于提交是“有效的”。每一次成功   control的控制名称与其当前值配对   提交的表单数据集

简单来说,使用多部分表单数据,您可以向服务器发送不同内容类型的数据。这是一个样本:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

这是一个发送三个不同集合的示例 - 第一个是binary data,第二个是plain text,第三个是html,它们是由边界分隔的。

现在如何工作Spring's RestTemplate

当您将请求标头设置为multipart/form-data时,resttemplate将从已注册的邮件转换器中选择适当的HttpMessageConvertermultipart/form-data FormHttpMessageConverterFormHttpMessageConverter查看文档{{3} }。

但是partConverters的属性为FormHttpMessageConverter,它们是为public FormHttpMessageConverter() { this.supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); this.supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA); this.partConverters.add(new ByteArrayHttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); this.partConverters.add(stringHttpMessageConverter); this.partConverters.add(new ResourceHttpMessageConverter()); } 注册的转换器,默认情况下是(字符串,字节数组和资源)。这是构造函数的源代码;)

FormHttpMessageConverter

简单地说,Post无法找到正确的消息转换器来编写对象Post。如果您希望将MappingJackson2HttpMessageConverter写为JSON,则应将partConverters添加到@Produces public RestTemplate getRestTemplate() { RestTemplate template = new RestTemplate(); template.getMessageConverters().add(0,createFormHttpConverter()); return template; } private static HttpMessageConverter<?> createFormHttpConverter(){ FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); formHttpMessageConverter.setPartConverters(getPartConverters()); return formHttpMessageConverter; } private static List<HttpMessageConverter<?>> getPartConverters(){ RestTemplate template = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); List<HttpMessageConverter<?>> messageConverters = template.getMessageConverters(); messageConverters.add(0,converter); return messageConverters; }

         $inputJSON = file_get_contents('php://input');
         $input = json_decode($inputJSON, true);
         .....
         //Extracting the leadgenid and passing it to fetchlead

         function fetchLead($leadid) {
          try { 
            $form = new Lead($leadid);
            return $form->read()->{LeadFields::FIELD_DATA}; //array
          }
          catch (Exception $e) {
            error_log($e->getMessage());
          }
         }

答案 3 :(得分:0)

您需要告诉Spring如何将请求参数映射到您的对象。您可以通过实现Alexander建议的自定义HttpMessageConterter来实现此目的,但我有一个更简单的方法:使用命令对象(有时称为表单支持对象):

public class PostWithPicCommand() {
   public PostWithPic() {}; //Default constructor is required

   //name the variables like the request parameters!
   private Post post;
   private MultipartFile image;

   Getter and Setter!
}

@RequestMapping(value = "/uploadpostpic", method = RequestMethod.POST)
public Post uploadPostWithPic(PostWithPicCommand postWithPicCommand
      /*no @Param attribte for postWithPicCommand*/) {    
    ....
}

您需要配置/注册弹簧Multipart Resolver,并需要将请求作为多部分请求发送。

答案 4 :(得分:0)

我用这个做了类似的东西:

  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);