Spring中如何使用RestTemplate将MultipartFile类型数据发送给被调用方

被调用方代码

    @PostMapping("/certificateUpload")
    public Result<?> certificateUpload(@RequestPart("file") MultipartFile file,
                                       @RequestParam String certificateType) {
        return certificateService.certificateUpload(file, certificateType);
    }

调用方代码

    public Result<?> certificateUpload(MultipartFile file, String certificateType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        try {
            map.add("file",file.getResource());
            map.add("certificateType",certificateType);
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
            ResponseEntity<Result> response = restTemplate.exchange(certificateUploadUrl, HttpMethod.POST, requestEntity, Result.class);
            return response.getBody();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok("上传失败");
    }

注意:百度有的例子是获取到MultipartFile的InputStream流包装在InputStreamResource中放在map里。

实际上使用时被调用方会报错 Required request part 'file' is not present 。接收不到传过去的file

发现点进getResource()源码看注释就已经写的很清楚了

Return a Resource representation of this MultipartFile.This can be used as input to the RestTemplate or the WebClient to expose content length and the filename along with the InputStream.
Returns:this MultipartFile adapted to the Resource contract
Since:5.1

标红部分说明可以用于RestTemplate或WebClient

posted @   姜晓姜晓  阅读(514)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示