Resttemplate form/multipart: image + JSON in POST

假如想象 提交于 2019-12-05 05:45:33

If you want to use ByteArrayResource, simply register a ResourceHttpMessageConverter.

If you want to use a byte[], simply register a ByteArrayHttpMessageConverter.

The content type of the image part should be an image type, like image/png, not application/json.

You can set each individual part's data type with

HttpHeaders partHeaders = new HttpHeaders();
partHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<ByteArrayResource> bytesPart = new HttpEntity<ByteArrayResource>(bytes, partHeaders);

map.add("file", bytesPart);

Create your RestTemplate by providing your collection of HttpMessageConverters

HttpMessageConverter<Object> jackson = new MappingJackson2HttpMessageConverter();
HttpMessageConverter<Resource> resource = new ResourceHttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
formHttpMessageConverter.addPartConverter(jackson);
formHttpMessageConverter.addPartConverter(resource); // This is hope driven programming

RestTemplate restTemplate = new RestTemplate(Arrays.asList(jackson, resource, formHttpMessageConverter));

and your outermost HttpEntity should have a multipart content type

header.setContentType(MediaType.MULTIPART_FORM_DATA);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!