首页 > 解决方案 > 使用 RestTemplate 发送多部分请求

问题描述

我想向一些外部 API(使用 Spring Boot 创建)发出多部分请求,但我得到的只是Required request part 'file' is not present.

我知道外部 API 的源代码,但我无法修改它。它看起来像这样:

    @PostMapping("/upload")
    public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file){
        return ResponseEntity.ok().build();
    }

从我的应用程序中,我创建并发送请求,就像在以下代码段中一样:

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body
                = new LinkedMultiValueMap<>();
        body.add("file", "dupa".getBytes());

        HttpEntity<MultiValueMap<String, Object>> requestEntity
                = new HttpEntity<>(body, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate
                .postForEntity("http://api:8080/upload", requestEntity, String.class);
        return response.getBody();

它不起作用的原因是什么?上面使用 Apache HttpClient 重写的代码就像魅力一样。

标签: springspring-bootresttemplate

解决方案


你基本上有两个选择,字节数组的解决方案:

    map.add("file", new ByteArrayResource(byteArrayContent) {
        @Override
        public String getFilename() {
            return "yourFilename";
        }
    });

我记得只添加一个字节数组有问题,所以你也需要一个文件名并使用 ByteArrayResource。

或添加文件:

    map.add("file", new FileSystemResource(file));

推荐阅读