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

时间:2021-05-20

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

HttpClient工具类:

HttpClientUtil.java

package cn.com.ajava.util;import java.io.File;import java.io.Serializable;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import java.util.Map.Entry;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;/** * HttpClient工具类 * * @author 曾繁添 * @version 1.0 */public class HttpClientUtil{ public final static String Method_POST = "POST"; public final static String Method_GET = "GET"; /** * multipart/form-data类型的表单提交 * * @param form * 表单数据 */ public static String submitForm(MultipartForm form) { // 返回字符串 String responseStr = ""; // 创建HttpClient实例 HttpClient httpClient = new DefaultHttpClient(); try { // 实例化提交请求 HttpPost httpPost = new HttpPost(form.getAction()); // 创建MultipartEntityBuilder MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); // 追加普通表单字段 Map<String, String> normalFieldMap = form.getNormalField(); for (Iterator<Entry<String, String>> iterator = normalFieldMap.entrySet().iterator(); iterator.hasNext();) { Entry<String, String> entity = iterator.next(); entityBuilder.addPart(entity.getKey(), new StringBody(entity.getValue(), ContentType.create("text/plain", Consts.UTF_8))); } // 追加文件字段 Map<String, File> fileFieldMap = form.getFileField(); for (Iterator<Entry<String, File>> iterator = fileFieldMap.entrySet().iterator(); iterator.hasNext();) { Entry<String, File> entity = iterator.next(); entityBuilder.addPart(entity.getKey(), new FileBody(entity.getValue())); } // 设置请求实体 httpPost.setEntity(entityBuilder.build()); // 发送请求 HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); // 取得响应数据 HttpEntity resEntity = response.getEntity(); if (200 == statusCode) { if (resEntity != null) { responseStr = EntityUtils.toString(resEntity); } } } catch (Exception e) { System.out.println("提交表单失败,原因:" + e.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } return responseStr; } /** 表单字段Bean */ public class MultipartForm implements Serializable { /** 序列号 */ private static final long serialVersionUID = -2138044819190537198L; /** 提交URL **/ private String action = ""; /** 提交方式:POST/GET **/ private String method = "POST"; /** 普通表单字段 **/ private Map<String, String> normalField = new LinkedHashMap<String, String>(); /** 文件字段 **/ private Map<String, File> fileField = new LinkedHashMap<String, File>(); public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public Map<String, String> getNormalField() { return normalField; } public void setNormalField(Map<String, String> normalField) { this.normalField = normalField; } public Map<String, File> getFileField() { return fileField; } public void setFileField(Map<String, File> fileField) { this.fileField = fileField; } public void addFileField(String key, File value) { fileField.put(key, value); } public void addNormalField(String key, String value) { normalField.put(key, value); } }}

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

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

ServletUploadFile.java

package cn.com.ajava.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Enumeration;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * 文件上传Servlet * @author 曾繁添 */public class ServletUploadFile extends HttpServlet{ private static final long serialVersionUID = 1L; // 限制文件的上传大小 1G private int maxPostSize = 1000 * 1024 * 10; public ServletUploadFile() { super(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String contextPath = request.getSession().getServletContext().getRealPath("/"); String webDir = "uploadfile" + File.separator + "images" + File.separator; String systemPath = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ systemPath + "/"; request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 4); // 设置写入大小 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); // 设置文件上传最大大小 System.out.println(request.getContentType()); //获取action后面拼接的参数(如:http:///ajava/servlet/ServletUploadFile");File photoFile = new File(sddCardPath+"//data//me.jpg");form.addFileField("photo", photoFile);form.addNormalField("name", "曾繁添");form.addNormalField("tel", "15122946685");//提交表单HttpClientUtil.submitForm(form);

最后说明一下jar问题:

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

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章