代码实现
public static String postMultipartFileUtil(MultipartFile file, String data, String url, HttpServletRequest request, HttpServletResponse response) {
String result = "";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
//文件参数
builder.setCharset(Charset.forName("UTF-8")).addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
//处理其他参数
builder.addTextBody("personId", data);
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if (responseEntity != null) { // 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
logger.info("上传文件返回结果:{}", result);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}