【发布时间】:2018-02-18 21:09:34
【问题描述】:
我正在尝试使用 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);
例外:
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]
Upload 适用于 Content-Type MediaType.MULTIPART_FORM_DATA,但我使用的 REST 服务仅接受 image/jpg 作为 HTTP Content-Type。
谢谢。
【问题讨论】:
标签: post spring-boot resttemplate