resttemplate 上传文件
时间: 2023-09-29 11:05:51 浏览: 140
文件上传模板
使用 RestTemplate 上传文件的步骤如下:
1. 创建一个 MultiValueMap 对象并添加文件内容
```java
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(new File(filePath)));
```
2. 创建一个 HttpHeaders 对象并设置 Content-Type 为 multipart/form-data
```java
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
```
3. 创建一个 HttpEntity 对象并将 MultiValueMap 和 HttpHeaders 对象添加到其中
```java
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
```
4. 使用 RestTemplate 的 postForObject 方法上传文件
```java
String url = "http://example.com/upload";
String response = restTemplate.postForObject(url, requestEntity, String.class);
```
完整的示例代码如下:
```java
RestTemplate restTemplate = new RestTemplate();
String filePath = "/path/to/file";
// Create the request body with the file content
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", new FileSystemResource(new File(filePath)));
// Set the Content-Type header to multipart/form-data
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// Create the HttpEntity with the request body and headers
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// Upload the file using RestTemplate
String url = "http://example.com/upload";
String response = restTemplate.postForObject(url, requestEntity, String.class);
```
阅读全文