使用RestTemplate上传MultipartFile文件
以下是使用RestTemplate传输MultipartFile文件的示例代码:
RestTemplate restTemplate = new RestTemplate();
// 创建文件
File file = new File('path/to/file.txt');
MultipartFile multipartFile = new MockMultipartFile('file', file.getName(), 'text/plain', new FileInputStream(file));
// 创建请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 创建请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add('file', multipartFile);
// 创建请求实体
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// 发送请求
String url = 'http://localhost:8080/upload';
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
// 处理响应
if (response.getStatusCode() == HttpStatus.OK) {
System.out.println('文件上传成功');
} else {
System.out.println('文件上传失败');
}
在上面的示例中,我们首先创建了一个RestTemplate实例,然后创建了一个File对象和一个MultipartFile对象,表示要上传的文件。接着,我们创建了请求头和请求体,将文件添加到请求体中。最后,我们创建了一个请求实体,并使用RestTemplate发送了POST请求。如果响应状态码为200 OK,则说明文件上传成功,否则说明文件上传失败。
原文地址: https://www.cveoy.top/t/topic/nw7L 著作权归作者所有。请勿转载和采集!