Java实现表单提交(支持多文件同时上传)
在Android里面或者J2EE后台需要趴别人网站数据,模拟表单提交是一件很常见的事情,但是在Android里面要实现多文件上传,还要夹着普通表单字段上传,这下可能就有点费劲了,今天花时间整理了一个工具类,主要是借助于HttpClient,其实也很简单,看一下代码就非常清楚了
HttpClient工具类:
HttpClientUtil.java
packagecn.com.ajava.util; importjava.io.File; importjava.io.Serializable; importjava.util.Iterator; importjava.util.LinkedHashMap; importjava.util.Map; importjava.util.Map.Entry; importorg.apache.http.Consts; importorg.apache.http.HttpEntity; importorg.apache.http.HttpResponse; importorg.apache.http.client.HttpClient; importorg.apache.http.client.methods.HttpPost; importorg.apache.http.entity.ContentType; importorg.apache.http.entity.mime.MultipartEntityBuilder; importorg.apache.http.entity.mime.content.FileBody; importorg.apache.http.entity.mime.content.StringBody; importorg.apache.http.impl.client.DefaultHttpClient; importorg.apache.http.util.EntityUtils; /** *HttpClient工具类 * *@author曾繁添 *@version1.0 */ publicclassHttpClientUtil { publicfinalstaticStringMethod_POST="POST"; publicfinalstaticStringMethod_GET="GET"; /** *multipart/form-data类型的表单提交 * *@paramform *表单数据 */ publicstaticStringsubmitForm(MultipartFormform) { //返回字符串 StringresponseStr=""; //创建HttpClient实例 HttpClienthttpClient=newDefaultHttpClient(); try { //实例化提交请求 HttpPosthttpPost=newHttpPost(form.getAction()); //创建MultipartEntityBuilder MultipartEntityBuilderentityBuilder=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(),newStringBody(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(),newFileBody(entity.getValue())); } //设置请求实体 httpPost.setEntity(entityBuilder.build()); //发送请求 HttpResponseresponse=httpClient.execute(httpPost); intstatusCode=response.getStatusLine().getStatusCode(); //取得响应数据 HttpEntityresEntity=response.getEntity(); if(200==statusCode) { if(resEntity!=null) { responseStr=EntityUtils.toString(resEntity); } } }catch(Exceptione) { System.out.println("提交表单失败,原因:"+e.getMessage()); }finally { httpClient.getConnectionManager().shutdown(); } returnresponseStr; } /**表单字段Bean*/ publicclassMultipartFormimplementsSerializable { /**序列号*/ privatestaticfinallongserialVersionUID=-2138044819190537198L; /**提交URL**/ privateStringaction=""; /**提交方式:POST/GET**/ privateStringmethod="POST"; /**普通表单字段**/ privateMap<String,String>normalField=newLinkedHashMap<String,String>(); /**文件字段**/ privateMap<String,File>fileField=newLinkedHashMap<String,File>(); publicStringgetAction() { returnaction; } publicvoidsetAction(Stringaction) { this.action=action; } publicStringgetMethod() { returnmethod; } publicvoidsetMethod(Stringmethod) { this.method=method; } publicMap<String,String>getNormalField() { returnnormalField; } publicvoidsetNormalField(Map<String,String>normalField) { this.normalField=normalField; } publicMap<String,File>getFileField() { returnfileField; } publicvoidsetFileField(Map<String,File>fileField) { this.fileField=fileField; } publicvoidaddFileField(Stringkey,Filevalue) { fileField.put(key,value); } publicvoidaddNormalField(Stringkey,Stringvalue) { normalField.put(key,value); } } }
服务器端实现文件上传、并且读取参数方法:(借助于Apache的fileupload组件实现,实现了获取表单action后面直接拼接参数、表单普通项目、文件项目三种字段获取方法)
后台我就直接写了一个Servlet,具体代码如下:
ServletUploadFile.java
packagecn.com.ajava.servlet; importjava.io.File; importjava.io.IOException; importjava.io.PrintWriter; importjava.util.Enumeration; importjava.util.Iterator; importjava.util.List; importjavax.servlet.ServletException; importjavax.servlet.http.HttpServlet; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importorg.apache.commons.fileupload.FileItem; importorg.apache.commons.fileupload.disk.DiskFileItemFactory; importorg.apache.commons.fileupload.servlet.ServletFileUpload; /** *文件上传Servlet *@author曾繁添 */ publicclassServletUploadFileextendsHttpServlet { privatestaticfinallongserialVersionUID=1L; //限制文件的上传大小1G privateintmaxPostSize=1000*1024*10; publicServletUploadFile() { super(); } @Override protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException, IOException { doPost(request,response); } protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException, IOException { PrintWriterout=response.getWriter(); StringcontextPath=request.getSession().getServletContext().getRealPath("/"); StringwebDir="uploadfile"+File.separator+"images"+File.separator; StringsystemPath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+systemPath+"/"; request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { DiskFileItemFactoryfactory=newDiskFileItemFactory(); factory.setSizeThreshold(1024*4);//设置写入大小 ServletFileUploadupload=newServletFileUpload(factory); upload.setSizeMax(maxPostSize);//设置文件上传最大大小 System.out.println(request.getContentType()); //获取action后面拼接的参数(如:http://www.baidu.com?q=android) EnumerationenumList=request.getParameterNames(); while(enumList.hasMoreElements()){ Stringkey=(String)enumList.nextElement(); Stringvalue=request.getParameter(key); System.out.println(key+"="+value); } //获取提交表单项目 ListlistItems=upload.parseRequest(request); Iteratoriterator=listItems.iterator(); while(iterator.hasNext()) { FileItemitem=(FileItem)iterator.next(); //非普通表单项目 if(!item.isFormField()) { //获取扩展名 Stringext=item.getName().substring(item.getName().lastIndexOf("."),item.getName().length()); StringfileName=System.currentTimeMillis()+ext; FiledirFile=newFile(contextPath+webDir+fileName); if(!dirFile.exists()) { dirFile.getParentFile().mkdirs(); } item.write(dirFile); System.out.println("fileName:"+item.getName()+"====="+item.getFieldName()+"size:"+item.getSize()); System.out.println("文件已保存到:"+contextPath+webDir+fileName); //响应客户端请求 out.print(basePath+webDir.replace("\\","/")+fileName); out.flush(); }else{ //普通表单项目 System.out.println("表单普通项目:"+item.getFieldName()+"="+item.getString("UTF-8"));//显示表单内容。item.getString("UTF-8")可以保证中文内容不乱码 } } }catch(Exceptione) { e.printStackTrace(); }finally { out.close(); } } }
工具类、服务器端代码上面都贴出来了,具体怎么调用应该就不需要说了吧?封装的已经够清晰明了了
调用示例DEMO:
//创建HttpClientUtil实例 HttpClientUtilhttpClient=newHttpClientUtil(); MultipartFormform=httpClient.newMultipartForm(); //设置form属性、参数 form.setAction("http://192.168.1.7:8080/UploadFileDemo/cn/com/ajava/servlet/ServletUploadFile"); FilephotoFile=newFile(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官网下载吧
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持毛票票!