发送端
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.3</version>
</dependency>
2.发送端
//需要传入的文件
File file = new File("D:/copyright.jsp");
CloseableHttpClient httpClient = HttpClients.createDefault();
//url 调用接口传递文件
HttpPost httpPost = new HttpPost("http://" +url);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fileInputStream.read(buffer);
fileInputStream.close();
InputStream inputStream = new ByteArrayInputStream(buffer);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
// 把文件加到HTTP的post请求中
builder.addBinaryBody("files", inputStream, ContentType.MULTIPART_FORM_DATA, file.getName());
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity responseEntity = response.getEntity();
String responseJsonString = EntityUtils.toString(responseEntity, "UTF-8");
log.info("调用上传文件接口返回结果===>>" + responseJsonString);
inputStream.close();
3.接收端
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) throws IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("files");// 获取上传文件对象
File savefile = new File("D://copyrightCopy.jsp");
FileCopyUtils.copy(file.getBytes(), savefile);
}