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
分类:
个人学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律