Java实现以form-data形式文件上传到服务器
package com.joolun.cloud.mall.common.util;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import lombok.extern.slf4j.Slf4j;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.config.RequestConfig;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.springframework.web.multipart.MultipartFile;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.util.Map;@Slf4jpublic class HttpFileUtil {public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {log.info("文件参数名称"+fileParamName);// 创建Http实例CloseableHttpClient httpClient = HttpClients.createDefault();// 创建HttpPost实例HttpPost httpPost = new HttpPost(url);// 请求参数配置RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).setConnectionRequestTimeout(10000).build();httpPost.setConfig(requestConfig);//请求头设置try {MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setCharset(StandardCharsets.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)));}log.info("builder"+builder);HttpEntity entity = builder.build();httpPost.setEntity(entity);log.info("请求url:"+url);log.info("请求参数:"+paramMap.toString());// 执行提交HttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 返回String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);log.info("请求返回数据"+res);JSONObject resJson= JSON.parseObject(res);if ("200".equals(resJson.get("code").toString())) {JSONObject data = (JSONObject) resJson.get("data");return data.get("fileUrl").toString();}return res;}} catch (Exception e) {e.printStackTrace();} finally {if (httpClient != null) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}return null;}}
来源地址:https://blog.csdn.net/XuDream/article/details/130583756