Search code examples
javamultipartform-dataresttemplatemultipartspring-resttemplate

Send Multipart form-data resttemplate?


I am trying to send the multipart-form data using resttemplate, but it is not working and seems data it is not reaching on server.

    public ResponseEntity<Map> postImage(URI postURL, String base64) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic basicAuthString");
    headers.add("Content-Type","multipart/form-data");
    base64 =  "base64String";

    MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
    form.add("$myPicture", base64);

    RestTemplate restTemplate = new RestTemplate();
    FormHttpMessageConverter converter = new FormHttpMessageConverter();
   // converter.setCharset(Charset.forName("UTF-8"));
    restTemplate.getMessageConverters().add(converter);

    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(form, headers);
    ResponseEntity<Map> responseObject = restTemplate.postForEntity(postURL, requestEntity, Map.class);
    return responseObject;
}

But same API is working as expected using curl.

 curl -i -X POST -H "Content-Type:multipart/form-data" ^
 -H "Authorization: Basic basicAuth" ^
 -F $myPicture = "base64String" ^
http://{{host}}:{{port}}/WebSDK/entity?q=entity={{entityGUID}},Picture=$myPicture

I tried various ways to get it worked but was unable to find out any resolution from this if possible could someone please guide me here...

Thanks in advance !!


Solution

  • To Fix this scenario I was in need to provide my base64 Encoded String as InputStream.

       class MultipartInputStreamFileResource extends InputStreamResource {
        private final String filename;
        MultipartInputStreamFileResource(InputStream inputStream, String filename) {
            super(inputStream);
            this.filename = filename;
        }
        @Override
        public String getFilename() {
            return this.filename;
        }
        @Override
        public long contentLength() throws IOException {
            return -1; // we do not want to generally read the whole stream into memory ...
        }
    }
    
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setContentLength(requestBody.length());
    
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("$myPicture", new MultipartInputStreamFileResource(IOUtils.toInputStream(requestBody), filename));
        HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(body, headers);
    

    providing this InputStreamResource instance in the request body helped to fix my issue.

    Thanks .