Java 客户端上传到服务器

说明:解决上传文件乱码问题,上传文件件,附带参数等。

引入包:


org.apache.httpcomponentshttpclient4.5.2

org.apache.httpcomponentshttpclient-cache4.5.2

org.apache.httpcomponentshttpmime4.5.2

org.apache.httpcomponentshttpcore4.4.6

客户端代码


public class HttpClientUploadUtils {

private static Log logger = LogFactory.getLog(HttpClientUploadUtils.class);

/** * 全新客户注册上传到crm服务器文件 

* * @param tempdirPath1 

* @param tempdirPath2 

* @param tempdirPath3 

* @param url * @return */public static ReturnDto uploadRegisterFile(String tempdirPath1, String tempdirPath2, String tempdirPath3,String url) {ReturnDto rt = new ReturnDto();// 1:创建一个CloseableHttpClient对象 ,CloseableHttpClient client = HttpClients.createDefault();String responseContent = null; // 响应内容CloseableHttpResponse response = null;try {// 2:创建http的发送方式对象,是GET还是post,url后面可以携带参数HttpPost post = new HttpPost(url);// 3. 一定要写成这个编码模式MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);// multipartEntityBuilder.setMode 问题就出现在这里,设置模式时,应该设置成HttpMultipartMode.RFC6532 才没有出现乱码FileBody bin1 = new FileBody(new File(tempdirPath1));FileBody bin2 = new FileBody(new File(tempdirPath2));FileBody bin3 = new FileBody(new File(tempdirPath3));ArrayList fileBodys = new ArrayList<>();

fileBodys.add(bin1);

fileBodys.add(bin2);

fileBodys.add(bin3);

File file1 = new File(tempdirPath1);

File file2 = new File(tempdirPath2);

File file3 = new File(tempdirPath3);

//上传多个文件

multipartEntityBuilder.addBinaryBody("file1", file1);

multipartEntityBuilder.addBinaryBody("file2", file2);

multipartEntityBuilder.addBinaryBody("file3", file3);

HttpEntity reqEntity = multipartEntityBuilder.build();

post.setEntity(reqEntity);

response = client.execute(post);

if (response.getStatusLine().getStatusCode() == 200) {

HttpEntity entity = response.getEntity();

responseContent = EntityUtils.toString(entity, "UTF-8");

System.out.print(responseContent);

// 解析返回的json数据

// boolean isSuccess = object.getJSONObject("result").getBoolean("success");

}

// 获取返回状态

int statusCode = response.getStatusLine().getStatusCode();

logger.info("获取返回状态statusCode = " + statusCode);

if (statusCode == HttpStatus.SC_OK) {

System.out.println("服务器正常响应.....");

/*

* HttpEntity resEntity3 = response.getEntity();

* System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据

* System.out.println(resEntity.getContent()); EntityUtils.consume(resEntity3);

*/

}

rt.setErrCode(Constants.RT_SUCCESSCODE);

rt.setErrMsg(Constants.RT_SUCCESSMSG);

} catch (UnsupportedEncodingException e) {

rt.setErrCode(Constants.RT_EXCEPTIONCODE);

rt.setErrMsg(e.getMessage());

e.printStackTrace();

} catch (IllegalStateException e) {

rt.setErrCode(Constants.RT_EXCEPTIONCODE);

rt.setErrMsg(e.getMessage());

e.printStackTrace();

} catch (IOException e) {

rt.setErrCode(Constants.RT_EXCEPTIONCODE);

rt.setErrMsg(e.getMessage());

e.printStackTrace();

} finally {

try {

if (response != null)

response.close();

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (client != null)

client.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return rt;

}

}

服务器代码


// 限制上传文件的类型public static String exts = "pptx,docx,doc";public static int fileMaxSize = 1024 * 1024 * 20; // 单个文件大小20MBpublic static int totalFileMaxSize = 1024 * 1024 * 10 * 10;// 所有文件总大小100MBpublic static String APP_DIR = AppDir.get();private static final String RELATIVEFILE_DIR = File.separator + "WEB-INF" + File.separator + "file" + File.separator+ "uploadfile" + File.separator + "custfile" + File.separator;@Overridepublic Object execute(HttpServletRequest request, CLog log) throws Exception {String errorMsg = "";// 上传成功文件名集合ListfileNameList = new ArrayList();MaprequestMap = new HashMap();String opid = (String) request.getSession().getAttribute("opid");String custno = (String) request.getParameter("pi_custno");requestMap.put("opid", opid);String tempdir = APP_DIR + RELATIVEFILE_DIR + custno + File.separator;File tempdirfilepath = new File(tempdir);if (!tempdirfilepath.exists()) {tempdirfilepath.mkdirs();}Mapresult = new HashMap();List> retlist = new ArrayList>();Mapmap = new HashMap();// 接收文件boolean isMultipart = ServletFileUpload.isMultipartContent(request);// 判断是否是文件上传请求if (!isMultipart) {result.put(Constants.StdRetCodeFieldName, "0001");// retcoderesult.put(Constants.StdRetMsgFieldName, "操作失败");// retmsgmap.put("code", "0001");errorMsg = errorMsg + "Error : 非文件上传文件请求,表单必须包含 enctype=multipart/form-data";map.put("msg", errorMsg);// out.println("Error : 表单必须包含 enctype=multipart/form-data");// return;retlist.add(map);result.put(HKCRMSP.RetCursorFieldName, retlist);// po_cursorreturn result;}// 用于创建解析文件上传的工厂类DiskFileItemFactory factory = new DiskFileItemFactory();// 用于从请求中解析出文件ServletFileUpload upload = new ServletFileUpload(factory);// 解决上传文件名的中文乱码upload.setHeaderEncoding("UTF-8");// 定义一个输出流FileOutputStream fos = null;BufferedInputStream bis = null;try {// 设置上传单个文件的大小的最大值,目前是设置为1024*1024*3字节,也就是3MBupload.setFileSizeMax(fileMaxSize);// 设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MBupload.setSizeMax(totalFileMaxSize);// 获取所有提交过来的文件(包含表单内容) 这个FileItem叫做一个项,这个项有可能是文件也有可能是表单参数Listitems = upload.parseRequest(request);// 缓冲区byte[] buf = new byte[8192];if (items != null && items.size() > 0) { // 不为空且长度大于0则遍历之// 多个文件的遍历for (FileItem item : items) {if (item.isFormField()) {// isFormField = true 文本框的值// out.println("用户名: " + item.getString() + "

");String str = "用户名: " + item.getString() + "

";result.put(Constants.StdRetCodeFieldName, "0001");// retcoderesult.put(Constants.StdRetMsgFieldName, "操作失败");// retmsgmap.put("code", "0001");map.put("msg", str);} else {String fileName = item.getName();System.out.println("打印文件名 = "+fileName);if (fileName.endsWith(".pdf") || fileName.endsWith(".PNG") || fileName.endsWith(".png")|| fileName.endsWith(".jpg") || fileName.endsWith(".JPG") || fileName.endsWith(".xlsx")|| fileName.endsWith(".xls") || fileName.endsWith(".docx")|| fileName.endsWith(".doc")) {// 获取输入流bis = new BufferedInputStream(item.getInputStream());String filename = item.getName();System.out.println("打印解码前的文件名="+filename);//无需转码// 初始化本地输出流// fos = new FileOutputStream(new File(TEMP_PATH + "/" + item.getName()));fos = new FileOutputStream(new File(tempdir + filename));int len = -1;while ((len = bis.read(buf)) != -1) {fos.write(buf, 0, len);fos.flush();}// out.println("文件: " + item.getName() + "已上传

");map.put("msg", "文件: " + item.getName() + "已上传成功

");// out.println("文件: " + item.getName() + "已上传成功

");// filePath = tempdir + item.getName();// 保存上传成功的文件名fileNameList.add(filename);} else {errorMsg = errorMsg + "支持上传pdf、png、jpg、docx、doc、xlsx、xls文件格式!

";result.put(Constants.StdRetCodeFieldName, "0001");// retcoderesult.put(Constants.StdRetMsgFieldName, "操作失败");// retmsgmap.put("code", "0001");map.put("msg", errorMsg);}// 这儿需要关闭流,不然多个文件的时候会删除失败,finally里面只会关闭最后一个流if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}// System.out.println("生成文件的文件名filename=" + filename);// System.out.println("生成文件的相对路径relativeFilePath=" + relativeFilePath);}}}} catch (FileUploadException e) {// out.println("Error: 文件解析异常");System.out.println("文件上传异常FileUploadException=" + e.getMessage());result.put(Constants.StdRetCodeFieldName, "0001");// retcoderesult.put(Constants.StdRetMsgFieldName, "操作失败");// retmsgmap.put("code", "0001");errorMsg = "上传异常:" + e.getMessage();map.put("msg", errorMsg);e.printStackTrace();} catch (Exception e2) {System.out.println("上传异常Exception=" + e2.getMessage());result.put(Constants.StdRetCodeFieldName, "0001");// retcoderesult.put(Constants.StdRetMsgFieldName, "操作失败");// retmsgerrorMsg = "上传异常error:" + e2.getMessage();map.put("code", "0001");map.put("msg", errorMsg);e2.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}if (bis != null) {try {bis.close();} catch (IOException e) {e.printStackTrace();}}}int uploadPathIndex = 0;// 相对路径插入数据库if (fileNameList.size() > 0) {for (int i = 0; i < fileNameList.size(); i++) {String tempFileName = fileNameList.get(i);// System.out.println("打印遍历文件名集合文件名="+tempFileName);String tempRelativeFilePath = RELATIVEFILE_DIR + custno + File.separator + tempFileName;// 调用存储过程Mapinmap = new HashMap();inmap.put("spname", "osp_custinfofile_mod");inmap.put("pi_opid", opid);inmap.put("pi_custno", custno);inmap.put("pi_filepath", tempRelativeFilePath);inmap.put("pi_filename", tempFileName);Map resultMap = HKCRMSP.call(inmap, log);

System.out.println("上传文件信息处理存储结果=" + resultMap);

if (resultMap.get("po_retcode").equals("0000")) {

uploadPathIndex++;

map.put("code", "0000");

map.put("msg", uploadPathIndex + "个文件上传成功!失败:" + (fileNameList.size() - uploadPathIndex) + "个");

} else {

map.put("code", "0001");

map.put("msg", uploadPathIndex + "个文件上传成功!失败文件err:" + resultMap.get("po_retmsg"));

}

result.put(Constants.StdRetCodeFieldName, resultMap.get(Constants.StdRetCodeFieldName));// retcode

result.put(Constants.StdRetMsgFieldName, resultMap.get(Constants.StdRetMsgFieldName));// retmsg

}

if (uploadPathIndex == 0) {

map.put("code", "0001");

map.put("msg", "文件上传失败:" + errorMsg);

}

} else {

map.put("code", "0001");

map.put("msg", "文件上传失败:" + errorMsg);

}

retlist.add(map);

result.put(HKCRMSP.RetCursorFieldName, retlist);// po_cursor

return result;

}

你可能感兴趣的:(Java 客户端上传到服务器)