使用Spring boot RestTemplate上传文件
时间: 2023-01-29 09:12:10 浏览: 86
使用 Spring Boot RestTemplate 上传文件的一种方法是创建一个 `MultiValueMap`,将文件作为键值对添加到该 `MultiValueMap` 中,然后将其作为请求体发送到服务器。这里是一个示例代码:
```
@Autowired
private RestTemplate restTemplate;
public void uploadFile(String url, File file) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(file));
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
}
```
在这段代码中,我们创建了一个 `MultiValueMap`,并将文件作为键值对添加到该 `MultiValueMap` 中。然后,我们创建了一个带有该 `MultiValueMap` 的请求实体,并使用 RestTemplate 的 `exchange` 方法将其发送到服务器。请注意,在这种情况下,Content-Type 头设置为 `multipart/form-data`,因为我们正在上传一个文件。
希望这能帮到你!