RestTemplate将图像上传为具有Content-Type image / jpg的MultipartFile

时间:2017-09-10 14:42:11

标签: post spring-boot resttemplate

我正在尝试使用RestTemplate将图像(MultipartFile)上传到服务器URL。 来自邮递员的发送请求使用Content-Type: image/jpg和从Body发送为二进制文件的图像。

SpringBoot中的方法实现:

public ResponseEntity<String> uploadImage(MultipartFile file) {
    restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
    restTemplate.getMessageConverters().add(new BufferedImageHttpMessageConverter());

    LinkedMultiValueMap<String,Object> params = new LinkedMultiValueMap<>();
    params.add("file", new FileSystemResource(file));
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.IMAGE_JPEG);
    HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, httpHeaders);

    return restTemplate.exchange(UPLOAD_URL, HttpMethod.POST, requestEntity, String.class);

例外:

org.springframework.web.client.RestClientException: Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.util.LinkedMultiValueMap] and content type [image/jpeg]

上传适用于Content-Type MediaType.MULTIPART_FORM_DATA,但我使用的REST服务只接受image/jpg作为HTTP Content-Type。

感谢。

1 个答案:

答案 0 :(得分:0)

您的远程服务接受image/jpg,因此您应该流传输字节而不是多部分内容:

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "image/jpeg");

Resource res = new InputStreamResource(file.getInputStream());

HttpEntity<Resource> entity = new HttpEntity<>(res, headers);
template.exchange(UPLOAD_URL, HttpMethod.POST, entity , String.class);

RestTemplate具有ResourceHttpMessageConverter,可将您的多部分内容流式传输给您的服务。