欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-08 10:58:04
在android里面或者j2ee后台需要趴别人网站数据,模拟表单提交是一件很常见的事情,但是在android里面要实现多文件上传,还要夹着普通表单字段上传,这下可能就有点费...

在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://www.baidu.com?q=android)
 enumeration enumlist = request.getparameternames();
 while(enumlist.hasmoreelements()){
 string key = (string)enumlist.nextelement();
 string value = request.getparameter(key);
 system.out.println(key+"="+value);
 }
 //获取提交表单项目
 list listitems = upload.parserequest(request);
 iterator iterator = listitems.iterator();
 while (iterator.hasnext())
 {
 fileitem item = (fileitem) iterator.next();
 //非普通表单项目
 if (!item.isformfield())
 {
  //获取扩展名
  string ext = item.getname().substring(item.getname().lastindexof("."), item.getname().length());
  string filename = system.currenttimemillis() + ext;
  file dirfile = new file(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 (exception e)
 {
 e.printstacktrace();
 } finally
 {
 out.close();
 }
 }
}

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

调用示例demo:

//创建httpclientutil实例
httpclientutil httpclient = new httpclientutil();
multipartform form = httpclient.new multipartform();
//设置form属性、参数
form.setaction("http://192.168.1.7:8080/uploadfiledemo/cn/com/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官网下载吧

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