在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java实现表单提交(支持多文件同时上传)

2017-3-7 12:52| 发布者: zhangjf| 查看: 1381| 评论: 0

摘要: 在Android里面或者J2EE后台需要趴别人网站数据,模拟表单提交是一件很常见的事情,但是在Android里面要实现多文件上传,还要夹着普通表单字段上传,这下可能就有点费劲了,今天花时间整理了一个工具类,主要是借助于 ...

在Android里面或者J2EE后台需要趴别人网站数据,模拟表单提交是一件很常见的事情,但是在Android里面要实现多文件上传,还要夹着普通表单字段上传,这下可能就有点费劲了,今天花时间整理了一个工具类,主要是借助于HttpClient,其实也很简单,看一下代码就非常清楚了

HttpClient工具类:

HttpClientUtil.java

  1. package cn.com.ajava.util;
  2. import java.io.File;
  3. import java.io.Serializable;
  4. import java.util.Iterator;
  5. import java.util.LinkedHashMap;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8. import org.apache.http.Consts;
  9. import org.apache.http.HttpEntity;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.entity.ContentType;
  14. import org.apache.http.entity.mime.MultipartEntityBuilder;
  15. import org.apache.http.entity.mime.content.FileBody;
  16. import org.apache.http.entity.mime.content.StringBody;
  17. import org.apache.http.impl.client.DefaultHttpClient;
  18. import org.apache.http.util.EntityUtils;
  19. /**
  20. * HttpClient工具类
  21. *
  22. * @author 曾繁添
  23. * @version 1.0
  24. */
  25. public class HttpClientUtil
  26. {
  27. public final static String Method_POST = "POST";
  28. public final static String Method_GET = "GET";
  29. /**
  30. * multipart/form-data类型的表单提交
  31. *
  32. * @param form
  33. * 表单数据
  34. */
  35. public static String submitForm(MultipartForm form)
  36. {
  37. // 返回字符串
  38. String responseStr = "";
  39. // 创建HttpClient实例
  40. HttpClient httpClient = new DefaultHttpClient();
  41. try
  42. {
  43. // 实例化提交请求
  44. HttpPost httpPost = new HttpPost(form.getAction());
  45. // 创建MultipartEntityBuilder
  46. MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
  47. // 追加普通表单字段
  48. Map<String, String> normalFieldMap = form.getNormalField();
  49. for (Iterator<Entry<String, String>> iterator = normalFieldMap.entrySet().iterator(); iterator.hasNext();)
  50. {
  51. Entry<String, String> entity = iterator.next();
  52. entityBuilder.addPart(entity.getKey(), new StringBody(entity.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
  53. }
  54. // 追加文件字段
  55. Map<String, File> fileFieldMap = form.getFileField();
  56. for (Iterator<Entry<String, File>> iterator = fileFieldMap.entrySet().iterator(); iterator.hasNext();)
  57. {
  58. Entry<String, File> entity = iterator.next();
  59. entityBuilder.addPart(entity.getKey(), new FileBody(entity.getValue()));
  60. }
  61. // 设置请求实体
  62. httpPost.setEntity(entityBuilder.build());
  63. // 发送请求
  64. HttpResponse response = httpClient.execute(httpPost);
  65. int statusCode = response.getStatusLine().getStatusCode();
  66. // 取得响应数据
  67. HttpEntity resEntity = response.getEntity();
  68. if (200 == statusCode)
  69. {
  70. if (resEntity != null)
  71. {
  72. responseStr = EntityUtils.toString(resEntity);
  73. }
  74. }
  75. } catch (Exception e)
  76. {
  77. System.out.println("提交表单失败,原因:" + e.getMessage());
  78. } finally
  79. {
  80. httpClient.getConnectionManager().shutdown();
  81. }
  82. return responseStr;
  83. }
  84. /** 表单字段Bean */
  85. public class MultipartForm implements Serializable
  86. {
  87. /** 序列号 */
  88. private static final long serialVersionUID = -2138044819190537198L;
  89. /** 提交URL **/
  90. private String action = "";
  91. /** 提交方式:POST/GET **/
  92. private String method = "POST";
  93. /** 普通表单字段 **/
  94. private Map<String, String> normalField = new LinkedHashMap<String, String>();
  95. /** 文件字段 **/
  96. private Map<String, File> fileField = new LinkedHashMap<String, File>();
  97. public String getAction()
  98. {
  99. return action;
  100. }
  101. public void setAction(String action)
  102. {
  103. this.action = action;
  104. }
  105. public String getMethod()
  106. {
  107. return method;
  108. }
  109. public void setMethod(String method)
  110. {
  111. this.method = method;
  112. }
  113. public Map<String, String> getNormalField()
  114. {
  115. return normalField;
  116. }
  117. public void setNormalField(Map<String, String> normalField)
  118. {
  119. this.normalField = normalField;
  120. }
  121. public Map<String, File> getFileField()
  122. {
  123. return fileField;
  124. }
  125. public void setFileField(Map<String, File> fileField)
  126. {
  127. this.fileField = fileField;
  128. }
  129. public void addFileField(String key, File value)
  130. {
  131. fileField.put(key, value);
  132. }
  133. public void addNormalField(String key, String value)
  134. {
  135. normalField.put(key, value);
  136. }
  137. }
  138. }
复制代码

服务器端实现文件上传、并且读取参数方法:(借助于Apache的fileupload组件实现,实现了获取表单action后面直接拼接参数、表单普通项目、文件项目三种字段获取方法)

后台我就直接写了一个Servlet,具体代码如下:

ServletUploadFile.java

  1. package cn.com.ajava.servlet;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.Enumeration;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import org.apache.commons.fileupload.FileItem;
  13. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  14. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  15. /**
  16. * 文件上传Servlet
  17. * @author 曾繁添
  18. */
  19. public class ServletUploadFile extends HttpServlet
  20. {
  21. private static final long serialVersionUID = 1L;
  22. // 限制文件的上传大小 1G
  23. private int maxPostSize = 1000 * 1024 * 10;
  24. public ServletUploadFile()
  25. {
  26. super();
  27. }
  28. @Override
  29. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
  30. IOException
  31. {
  32. doPost(request, response);
  33. }
  34. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
  35. IOException
  36. {
  37. PrintWriter out = response.getWriter();
  38. String contextPath = request.getSession().getServletContext().getRealPath("/");
  39. String webDir = "uploadfile" + File.separator + "images" + File.separator;
  40. String systemPath = request.getContextPath();
  41. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ systemPath + "/";
  42. request.setCharacterEncoding("UTF-8");
  43. response.setContentType("text/html;charset=UTF-8");
  44. try
  45. {
  46. DiskFileItemFactory factory = new DiskFileItemFactory();
  47. factory.setSizeThreshold(1024 * 4); // 设置写入大小
  48. ServletFileUpload upload = new ServletFileUpload(factory);
  49. upload.setSizeMax(maxPostSize); // 设置文件上传最大大小
  50. System.out.println(request.getContentType());
  51. //获取action后面拼接的参数(如:http://www.baidu.com?q=android)
  52. Enumeration enumList = request.getParameterNames();
  53. while(enumList.hasMoreElements()){
  54. String key = (String)enumList.nextElement();
  55. String value = request.getParameter(key);
  56. System.out.println(key+"="+value);
  57. }
  58. //获取提交表单项目
  59. List listItems = upload.parseRequest(request);
  60. Iterator iterator = listItems.iterator();
  61. while (iterator.hasNext())
  62. {
  63. FileItem item = (FileItem) iterator.next();
  64. //非普通表单项目
  65. if (!item.isFormField())
  66. {
  67. //获取扩展名
  68. String ext = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length());
  69. String fileName = System.currentTimeMillis() + ext;
  70. File dirFile = new File(contextPath + webDir + fileName);
  71. if (!dirFile.exists())
  72. {
  73. dirFile.getParentFile().mkdirs();
  74. }
  75. item.write(dirFile);
  76. System.out.println("fileName:" + item.getName() + "=====" + item.getFieldName() + " size: "+ item.getSize());
  77. System.out.println("文件已保存到: " + contextPath + webDir + fileName);
  78. //响应客户端请求
  79. out.print(basePath + webDir.replace("\", "/") + fileName);
  80. out.flush();
  81. }else{
  82. //普通表单项目
  83. System.out.println("表单普通项目:"+item.getFieldName()+"=" + item.getString("UTF-8"));// 显示表单内容。item.getString("UTF-8")可以保证中文内容不乱码
  84. }
  85. }
  86. } catch (Exception e)
  87. {
  88. e.printStackTrace();
  89. } finally
  90. {
  91. out.close();
  92. }
  93. }
  94. }
复制代码

工具类、服务器端代码上面都贴出来了,具体怎么调用应该就不需要说了吧?封装的已经够清晰明了了

调用示例DEMO:

  1. //创建HttpClientUtil实例
  2. HttpClientUtil httpClient = new HttpClientUtil();
  3. MultipartForm form = httpClient.new MultipartForm();
  4. //设置form属性、参数
  5. form.setAction("http://192.168.1.7:8080/UploadFileDemo/cn/com/ajava/servlet/ServletUploadFile");
  6. File photoFile = new File(sddCardPath+"//data//me.jpg");
  7. form.addFileField("photo", photoFile);
  8. form.addNormalField("name", "曾繁添");
  9. form.addNormalField("tel", "15122946685");
  10. //提交表单
  11. HttpClientUtil.submitForm(form);
复制代码

最后说明一下jar问题:

要是android里面应用的话,需要注意一下额外引入httpmime-4.3.1.jar(我当时下的这个是最高版本了),至于fileUpload的jar,直接去apache官网下载吧

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持程序员之家!

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-8 06:35

Copyright 2015-2025 djqfx

返回顶部