The Apache Commons fileUpload file is uploaded to multiple sample shares

  • 2020-05-10 18:10:55
  • OfStack

This article introduces how to use commons-fileupload.jar, Apache's commons-fileupload.jar to upload files conveniently. The details are as follows

Put commons-fileupload.jar under WEB-INF \lib of the application and it is ready to use. Here's an example of how to use its file upload capabilities.

The version of fileUpload used is 1.2 and the environment is Eclipse3.3 + MyEclipse6.0. FileUpload is based on Commons IO, so before entering the project, make sure that the jar package of Commons IO (commons-io-1.3.2.jar is used in this paper) is under WEB-INF \lib.
This sample project can be downloaded in the attachment at the end of the article.

Example 1

The simplest example USES the ServletFileUpload static class to parse Request, and the factory class FileItemFactory handles all the fields in the form of the mulipart class, not just the file field. getName () gets the file name, getString () gets the form data content, and isFormField () determines if it is a normal form item.
demo1.html


<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>File upload</title>
</head>
<body>
    // It must be multipart Form data. 
  <form name="myform" action="demo1.jsp" method="post"
    enctype="multipart/form-data">
    Your name: <br>
    <input type="text" name="name" size="15"><br>
    File:<br>
    <input type="file" name="myfile"><br>
    <br>
    <input type="submit" name="submit" value="Commit">
  </form>
</body>
</html>

demo1.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
  pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);// Check if the input request is multipart Form data. 
  if (isMultipart == true) {
    FileItemFactory factory = new DiskFileItemFactory();// Create for the request 1 a DiskFileItemFactory Object through which the request is resolved. After parsing, all the form items are saved in 1 a List In the. 
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);
    Iterator<FileItem> itr = items.iterator();
    while (itr.hasNext()) {
      FileItem item = (FileItem) itr.next();
      // Check whether the current project is a normal form project or an uploaded file. 
      if (item.isFormField()) {// If it's a normal form item, display the form content. 
    String fieldName = item.getFieldName();
    if (fieldName.equals("name")) // The corresponding demo1.html In the type="text" name="name"
      out.print("the field name is" + item.getString());// Display the form content. 
    out.print("<br>");
      } else {// If you are uploading a file, display the file name. 
    out.print("the upload file name is" + item.getName());
    out.print("<br>");
      }
    }
  } else {
    out.print("the enctype must be multipart/form-data");
  }
%>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>File upload</title>
</head>
<body>
</body>
</html>

Results:
the field name isjeff
the upload file name isD:\C language test sample question \ problem set.rar

Example 2

Upload two files to the specified directory.

demo2.html


<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>File upload</title>
</head>
<body>
  <form name="myform" action="demo2.jsp" method="post"
    enctype="multipart/form-data">
    File1:<br>
    <input type="file" name="myfile"><br>
    File2:<br>
    <input type="file" name="myfile"><br>
    <br>
    <input type="submit" name="submit" value="Commit">
  </form>
</body>
</html>

demo2.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
  pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%String uploadPath="D:\\temp";
 boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 if(isMultipart==true){
   try{
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(request);// Get all the files 
    Iterator<FileItem> itr = items.iterator();
    while(itr.hasNext()){// Process each file in turn 
     FileItem item=(FileItem)itr.next();
     String fileName=item.getName();// Get the file name, including the path 
     if(fileName!=null){
       File fullFile=new File(item.getName());
       File savedFile=new File(uploadPath,fullFile.getName());
       item.write(savedFile);
     }
    }
    out.print("upload succeed");
   }
   catch(Exception e){
     e.printStackTrace();
   }
 }
 else{
   out.println("the enctype must be multipart/form-data");
 }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>

Results:
upload succeed

At this point, you can see the two files you uploaded under "D:\temp".

Example 3

Upload 1 file to the specified directory and limit the size of the file.

demo3.html


<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>File upload</title>
</head>
<body>
  <form name="myform" action="demo3.jsp" method="post"
    enctype="multipart/form-data">
    File:<br>
    <input type="file" name="myfile"><br>
    <br>
    <input type="submit" name="submit" value="Commit">
  </form>
</body>
</html>

demo3.jsp


<%@ page language="java" contentType="text/html; charset=GB18030"
  pageEncoding="GB18030"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%
  File uploadPath = new File("D:\\temp");// Upload file directory 
  if (!uploadPath.exists()) {
    uploadPath.mkdirs();
  }
  //  Temporary file directory 
  File tempPathFile = new File("d:\\temp\\buffer\\");
  if (!tempPathFile.exists()) {
    tempPathFile.mkdirs();
  }
  try {
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
 
    // Set factory constraints
    factory.setSizeThreshold(4096); //  Set the buffer size, here is 4kb
    factory.setRepository(tempPathFile);// Set buffer directory 
 
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
 
    // Set overall request size constraint
    upload.setSizeMax(4194304); //  Set the maximum file size, here is 4MB
 
    List<FileItem> items = upload.parseRequest(request);// Get all the files 
    Iterator<FileItem> i = items.iterator();
    while (i.hasNext()) {
      FileItem fi = (FileItem) i.next();
      String fileName = fi.getName();
      if (fileName != null) {
    File fullFile = new File(fi.getName());
    File savedFile = new File(uploadPath, fullFile
       .getName());
    fi.write(savedFile);
      }
    }
    out.print("upload succeed");
  } catch (Exception e) {
    e.printStackTrace();
  }
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>File upload</title>
</head>
<body>
</body>
</html>

Example 4

File upload using Servlet.

Upload.java


package com.zj.sample;
 
import java.io.File;
import java.io.IOException;
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;
 
@SuppressWarnings("serial")
public class Upload extends HttpServlet {
  private String uploadPath = "D:\\temp"; //  Directory of uploaded files 
  private String tempPath = "d:\\temp\\buffer\\"; //  Temporary file directory 
  File tempPathFile;
 
  @SuppressWarnings("unchecked")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    try {
      // Create a factory for disk-based file items
      DiskFileItemFactory factory = new DiskFileItemFactory();
 
      // Set factory constraints
      factory.setSizeThreshold(4096); //  Set the buffer size, here is 4kb
      factory.setRepository(tempPathFile);//  Set buffer directory 
 
      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
 
      // Set overall request size constraint
      upload.setSizeMax(4194304); //  Set the maximum file size, here is 4MB
 
      List<FileItem> items = upload.parseRequest(request);//  Get all the files 
      Iterator<FileItem> i = items.iterator();
      while (i.hasNext()) {
       FileItem fi = (FileItem) i.next();
       String fileName = fi.getName();
       if (fileName != null) {
         File fullFile = new File(fi.getName());
         File savedFile = new File(uploadPath, fullFile.getName());
         fi.write(savedFile);
       }
      }
      System.out.print("upload succeed");
    } catch (Exception e) {
      //  You can jump to the error page 
      e.printStackTrace();
    }
  }
 
  public void init() throws ServletException {
    File uploadFile = new File(uploadPath);
    if (!uploadFile.exists()) {
      uploadFile.mkdirs();
    }
    File tempPathFile = new File(tempPath);
    if (!tempPathFile.exists()) {
      tempPathFile.mkdirs();
    }
  }
}

  demo4.html


<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
  <title>File upload</title>
</head>
<body>
// action="fileupload" The corresponding web.xml In the <servlet-mapping> In the <url-pattern> The setting of the .
  <form name="myform" action="fileupload" method="post"
    enctype="multipart/form-data">
    File:<br>
    <input type="file" name="myfile"><br>
    <br>
    <input type="submit" name="submit" value="Commit">
  </form>
</body>
</html>

web.xml


<servlet>
  <servlet-name>Upload</servlet-name>
  <servlet-class>com.zj.sample.Upload</servlet-class>
</servlet>
 
<servlet-mapping>
  <servlet-name>Upload</servlet-name>
  <url-pattern>/fileupload</url-pattern>
</servlet-mapping>

Related articles: