Java implements form submission (multiple files can be uploaded simultaneously)
- 2020-05-30 20:03:40
- OfStack
In Android or J2EE background need to lie prone others site data, simulate the form submission is a very common thing, but in Android to achieve multiple file upload, even with ordinary form fields, this may be a bit difficult, today take time to organize a utility class, mainly by HttpClient, actually very simple, also see 1 under the code is very clear
HttpClient tool class:
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 Utility class
*
* @author Zeng Fantian
* @version 1.0
*/
public class HttpClientUtil
{
public final static String Method_POST = "POST";
public final static String Method_GET = "GET";
/**
* multipart/form-data Type of form submission
*
* @param form
* The form data
*/
public static String submitForm(MultipartForm form)
{
// Return string
String responseStr = "";
// create HttpClient The instance
HttpClient httpClient = new DefaultHttpClient();
try
{
// Instantiate the submit request
HttpPost httpPost = new HttpPost(form.getAction());
// create MultipartEntityBuilder
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// Appends normal form fields
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)));
}
// Append file field
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()));
}
// Set request entity
httpPost.setEntity(entityBuilder.build());
// Send the request
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
// Get response data
HttpEntity resEntity = response.getEntity();
if (200 == statusCode)
{
if (resEntity != null)
{
responseStr = EntityUtils.toString(resEntity);
}
}
} catch (Exception e)
{
System.out.println(" The submission of the form failed. Reasons: " + e.getMessage());
} finally
{
httpClient.getConnectionManager().shutdown();
}
return responseStr;
}
/** Form fields Bean */
public class MultipartForm implements Serializable
{
/** The serial number */
private static final long serialVersionUID = -2138044819190537198L;
/** submit URL **/
private String action = "";
/** Submission method: POST/GET **/
private String method = "POST";
/** Normal form field **/
private Map<String, String> normalField = new LinkedHashMap<String, String>();
/** The file field **/
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);
}
}
}
Server-side file upload and parameter reading method :(with the help of Apache's fileupload component implementation, it realizes the three methods of obtaining the fields directly after the form action: splicing parameters, form common items, and file items)
In the background, I directly wrote an Servlet, the specific code is as follows:
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;
/**
* File upload Servlet
* @author Zeng Fantian
*/
public class ServletUploadFile extends HttpServlet
{
private static final long serialVersionUID = 1L;
// Limit file upload size 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); // Set write size
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize); // Set the maximum file upload size
System.out.println(request.getContentType());
// To obtain action After the splicing parameter ( Such as: 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);
}
// Gets the submit form project
List listItems = upload.parseRequest(request);
Iterator iterator = listItems.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
// Not a normal form project
if (!item.isFormField())
{
// Get the extension
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(" File saved to: " + contextPath + webDir + fileName);
// Respond to client requests
out.print(basePath + webDir.replace("\\", "/") + fileName);
out.flush();
}else{
// Normal form items
System.out.println(" Form general items: "+item.getFieldName()+"=" + item.getString("UTF-8"));// Display the form content. item.getString("UTF-8") You can ensure that the Chinese content is not garbled
}
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
out.close();
}
}
}
Tool class, server code are posted above, the specific how to call should not need to say? The package is clear enough
Call example DEMO:
// create HttpClientUtil The instance
HttpClientUtil httpClient = new HttpClientUtil();
MultipartForm form = httpClient.new MultipartForm();
// Set up the form Properties, parameters
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", " Zeng Fantian ");
form.addNormalField("tel", "15122946685");
// Submit the form
HttpClientUtil.submitForm(form);
Finally, 1. The problem of jar:
If you are using android, please note that httpmime-4.3.1.jar (the version I used was the highest version at that time) will be introduced. As for jar of fileUpload, please go to the apache website to download it