程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java完成表單提交(支持多文件同時上傳)

Java完成表單提交(支持多文件同時上傳)

編輯:關於JAVA

Java完成表單提交(支持多文件同時上傳)。本站提示廣大學習愛好者:(Java完成表單提交(支持多文件同時上傳))文章只能為提供參考,不一定能成為您想要的結果。以下是Java完成表單提交(支持多文件同時上傳)正文


在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官網下載吧

以上就是本文的全部內容,希望本文的內容對大家的學習或許任務能帶來一定的協助,同時也希望多多支持!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved