一:引入pom.xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.3</version>
</dependency>
二:controller类实现
@PostMapping("/upload")
public JSONObject uploadOssFile(@RequestParam("files") MultipartFile files,
@RequestParam("param1") String param1,
@RequestParam("param2") String param2
HttpServletRequest request) throws IOException {
//获取上传文件 MultipartFile(图片,文件都可以)
Map<String, String> map = new HashMap<>();
map.put("param1", param1);
map.put("param2", param2);
return fileRemote.uploadFile(files, map);
}
三:fileRemote实现
public String getUrl() {
return "http://?????"; 文件上传的地址
}
/**
*
* @param multipartFile
* @param map
* @return
* @throws IOException
*/
public JSONObject uploadFile(MultipartFile multipartFile,
Map<String, String> map,
String toke) throws IOException {
return JSONObject.parseObject(HttpsUtils.doPostFormData(getUrl(),"files", multipartFile, map ));
}
四:HttpsUtils实现
/**
* 以post方式调用第三方接口,以form-data 形式 发送 MultipartFile 文件数据
*
* @param url post请求url
* @param fileParamName 文件参数名称
* @param multipartFile 文件
* @param paramMap 表单里其他参数
* @return
*/
public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {
CloseableHttpClient httpClient2 = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
//httpPost.setHeader("key", value); // 这里放请求头参数
// 请求参数配置
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
String fileName = multipartFile.getOriginalFilename();
// 文件流
builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
//表单中其他参数
for(Map.Entry<String, String> entry: paramMap.entrySet()) {
builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient2.execute(httpPost);// 执行提交
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回
String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
return res;
}
} catch (Exception e) {
e.printStackTrace();
log.error("调用HttpPost失败!" + e.toString());
} finally {
if (httpClient != null) {
try {
httpClient.close();
} catch (IOException e) {
log.error("关闭HttpPost连接失败!");
}
}
}
return null;
}