pubic class demo{
public void reciveMultipartAndSend(HttpServletRequest httpServletRequest){
InputStream openStream = null;
try {
Map<String, EsbBusFile> files = new HashMap<>();
Map<String, String> texts = new HashMap<>();
Map<String, String> origTexts=new HashMap<>();
// 判断是否是表单提交的数据
if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
ServletFileUpload fileUpload = new ServletFileUpload();
FileItemIterator fileItemIterator =
fileUpload.getItemIterator(httpServletRequest);
while (fileItemIterator.hasNext()) {
// 获取文件流
FileItemStream item = fileItemIterator.next();
// 返回表单中标签的name值
String name = item.getFieldName();
openStream = item.openStream();
if (item.isFormField()) {
// 如果是非文件域,设置进入map,这里要注意多值处理
if (openStream.available() > 0){
String value = Streams.asString(openStream);
origTexts.put(name, value);
texts.put(name,BASE64.decode(value));
}
} else {
// 如果输出流的内容大于0
if (openStream.available() > 0) {
// 将文件读入内存中
EsbBusFile file=new EsbBusFile();
// 将文件读入内存中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*8];
int len = 0;
while ((len = openStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
//原始文件名
String originFileName=item.getName();
file.setOriginFileName(originFileName);
file.setTargetFileName(originFileName);
// 获取文件扩展名
String fileExtName="";
if (originFileName != null && originFileName.lastIndexOf(".") >= 0) {
fileExtName = originFileName.substring(originFileName.lastIndexOf("."));
}
file.setFileExtName(fileExtName);
// 组装文件
byte[] fileBody= outputStream.toByteArray();
file.setFileBody(fileBody);
//文件大小
file.setFileSize(fileBody.length);
// 添加到集合
files.put(name, file);
}
}
}
String url = "";
// 开始转发请求
this.doPostMultipart(url, texts, files, 10000, 10000,null);
}
} catch (Exception e) {
throw new EsbBusException(e);
} finally {
// 释放资源
if (openStream != null) {
try {
openStream.close();
} catch (IOException e) {
logger.error("资源关闭异常" + e);
}
}
}
}
public static String doPostMultipart(String url, Map<String, String> texts, Map<String, EsbBusFile> files, int socketTimeout,
int connectTimeout, Map<String, String> header) throws Exception {
Date startTime=new Date();
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
HttpPost httpPost = null;
String result = null;
try {
// 设置请求路径
httpPost = new HttpPost(url);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
// 文件体
if (files != null) {
for (String fieldName : files.keySet()) {
multipartEntityBuilder.addBinaryBody(fieldName, files.get(fieldName).getFileBody(),
ContentType.DEFAULT_BINARY, files.get(fieldName).getTargetFileName());
}
}
// 封装参数
if (texts != null) {
for (String key : texts.keySet()) {
StringBody comment = new StringBody(texts.get(key), ContentType.TEXT_PLAIN);
multipartEntityBuilder.addPart(key, comment);
}
}
httpPost.setEntity(multipartEntityBuilder.build());
// 执行请求
httpClient=HttpClients.createDefault();
httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
result = EntityUtils.toString(httpResponse.getEntity(),ENCODE_CHARSET);
logger.info("doPostMultipart响应:" + url + ",结果:" + result);
// 返回结果
}
} catch (ConnectTimeoutException cte) {
throw new EsbBusException("请求通信[" + url + "]时连接超时", cte);
} catch (SocketTimeoutException ste) {
throw new EsbBusException("请求通信[" + url + "]时读取超时", ste);
} catch (ClientProtocolException cpe) {
throw new EsbBusException("请求通信[" + url + "]时协议异常", cpe);
} catch (ParseException pe) {
throw new EsbBusException("请求通信[" + url + "]时解析异常", pe);
} catch (IOException ioe) {
throw new EsbBusException("请求通信[" + url + "]时网络异常", ioe);
} catch (Exception e) {
throw new EsbBusException("请求通信[" + url + "]时偶遇异常", e);
} finally {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpPost != null) {
httpPost.releaseConnection();
}
if(httpClient!=null){
httpClient.close();
}
Date endTime=new Date();
logger.info("doPostMultipart耗时:" + url+",毫秒:"+(endTime.getTime()-startTime.getTime()));
logger.info("--------------------------------------------------------------------------");
}
return result;
}
}