1

I'm having issues uploading a file via resttemplate client on linux

Here's what I have currently

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
    form.add("image", new FileSystemResource(imageFile));
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(form, headers);
    UploadResponse response = restTemplate.postForEntity(uploadUrl,httpEntity, UploadResponse.class).getBody();

Code works fine on windows but returns this error on linux:

 I/O error on POST request for "https://baseurl/api/v1/upload": Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value
 at [Source: (StringReader); line: 1, column: 47]; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 13)): has to be escaped using backslash to be included in string value

Anyone has an idea what might be wrong?

4
  • Try to just print new FileSystemResource(imageFile) and see if it picks up the image file correctly on linux or not. Commented Nov 3, 2021 at 10:49
  • @SusanMustafa Yes it picks up the image correctly on linux Commented Nov 3, 2021 at 10:56
  • Curious, could you try to setContentType("multipart/form-data;charset=UTF-8"); instead. Lets see how it reacts. Commented Nov 3, 2021 at 11:14
  • Okay I'll try this Commented Nov 3, 2021 at 11:17

1 Answer 1

0

The solution to this seems to be to update your ObjectMapper to ignore CTRL characters, which Linux might be inferring

@Autowired
private ObjectMapper objectMapper;

@Autowired
private RestTemplate restTemplate;

private void patchRestTemplate() {

    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    restTemplate.getMessageConverters().forEach(httpMessageConverter -> {

        if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) {

            ((MappingJackson2HttpMessageConverter) httpMessageConverter).setObjectMapper(objectMapper);
        }
    });
}

Reference: JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

Sign up to request clarification or add additional context in comments.

3 Comments

Didn't work for me, got the same error
Are you actually patching the restTemplate before doing restTemplate.postForEntity??
I've just figured out the issue. Thanks very much. Your solution helped put me on the right path. an existing internal restTemplate client interceptor logger library I was using did not cater for logging "multipart/form-data" requests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.