【问题标题】:RestTemplate upload image as MultipartFile with Content-Type image/jpgRestTemplate 上传图像作为 MultipartFile 与 Content-Type image/jpg
【发布时间】: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


    【解决方案1】:

    您的远程服务接受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,它将您的多部分流式传输到您的服务。

    【讨论】:

    • 我现在收到此错误No HttpMessageConverter for org.springframework.core.io.InputStreamResource and content type "image/jpeg"
    • @Ron.Basco 将 InputStreamResource 声明更改为 Resource。查看我的编辑
    • @Ron.Basco 你注册ResourceHttpMessageConverter了吗? restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());
    • 我发现了问题。是因为我正在使用的其余模板。我在其余模板正在重新编码的 URL 中有静态参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2012-01-21
    • 1970-01-01
    • 2017-11-02
    • 2021-06-19
    • 2014-04-28
    • 2021-11-08
    相关资源
    最近更新 更多