spring - 使用 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 重写的代码就像魅力一样。
解决方案
你基本上有两个选择,字节数组的解决方案:
map.add("file", new ByteArrayResource(byteArrayContent) {
@Override
public String getFilename() {
return "yourFilename";
}
});
我记得只添加一个字节数组有问题,所以你也需要一个文件名并使用 ByteArrayResource。
或添加文件:
map.add("file", new FileSystemResource(file));
推荐阅读
- angular - 表单控件不适用于 Angular Material Mat-select
- reactjs - FullCalendar React 工具提示
- c# - SQLConnection to MariaDB localhost via .NetCore
- azure - 使用 aspnetcore3 执行 Azure 函数 v2 时出现异常 - 系统找不到指定的文件。System.Private.CoreLib
- bash - mailx sending email to multiple accounts
- mysql - MySQL Query - Create a Trigger that updates stock levels once a sale takes place
- xpath - Why importxml and importhtml not working here?
- php - 有没有办法手动添加订阅到 laravel 收银员订阅表
- xml - 使用命名空间的 XSL 转换
- vb.net - 将 IQueryable 转换为另一种类型会引发错误“System.NotsupportedException”