1.引入依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
2.模拟前端请求上传文件接口
public String upload() throws Exception{
// 文件路径
File file = new File("path/to/your/file.txt");
// 构建 HTTP 客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 构建 HTTP POST 请求
HttpPost httpPost = new HttpPost("http://localhost:8080/upload");
// 构建 multipart 请求体
HttpEntity multipartEntity = MultipartEntityBuilder.create()
//上传的文件
.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName())
//添加参数
.addTextBody("param1", "value1")
.addTextBody("param2", "value2")
.build();
httpPost.setEntity(multipartEntity);
// 发送请求并获取响应
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 输出响应
System.out.println("Response status: " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response body: " + EntityUtils.toString(entity));
return EntityUtils.toString(entity);
}
}
return "";
}
3.后端接受文件接口
@PostMapping("/upload")
public R uploadFil(FileInfo fileInfo, MultipartFile file) {
// 处理业务
}
补充:使用RestTemplate 发送请求
public String upload() throws Exception{
// 文件路径
File file = new File("path/to/your/file.txt");
// 创建 RestTemplate 实例
RestTemplate restTemplate = new RestTemplate();
// 构建 MultiValueMap 作为请求体
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
FileSystemResource fileResource = new FileSystemResource(file);
body.add("file", fileResource);
body.add("param1", "value1");
body.add("param2", "value2");
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// 创建 HttpEntity
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
// 发送 POST 请求
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/upload", requestEntity, String.class);
// 输出响应
System.out.println("Response status: " + response.getStatusCode());
System.out.println("Response body: " + response.getBody());
return response.getBody();
}
7293

被折叠的 条评论
为什么被折叠?



