使用RestTemplate发送多部分请求

时间:2019-08-29 20:14:17

标签: spring spring-boot resttemplate

我想对某些外部API(使用Spring Boot创建的)发出多部分请求,但我得到的只是p == NULL

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

Required request part 'file' is not present

从我的应用程序中,我创建并发送请求的方式与以下代码段完全相同:

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

什么原因不起作用?上面使用Apache HttpClient重写的代码的工作原理类似于魅力。

1 个答案:

答案 0 :(得分:2)

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

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

我记得刚添加字节数组时遇到了问题,因此您也需要有一个文件名并使用ByteArrayResource。

或添加文件:

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