RestTemplate 将图像上传为 MultipartFile,内容类型为 image/jpg

Mar*_*vic 5 post resttemplate spring-boot

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

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);
Run Code Online (Sandbox Code Playgroud)

例外:

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]
Run Code Online (Sandbox Code Playgroud)

上传适用于 Content-Type MediaType.MULTIPART_FORM_DATA,但我使用的 REST 服务仅接受image/jpgHTTP Content-Type。

谢谢。

Mạn*_*yễn 5

您的远程服务接受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);
Run Code Online (Sandbox Code Playgroud)

RestTemplate可以ResourceHttpMessageConverter将您的多部分流式传输到服务中。