In the Servlet using the Apache open-source library for file uploads

In this paper, specific examples, describes how the package provided by the Apache open-source library for file uploads in a Servlet. This article is the reference book "Tomcat and Java Web development technology explain," third edition, author: Sunweiqin.

As used herein, the software version is: Window10, JDK10, Tomcat9.
Download the source code of the website referred to herein as:
http://www.javathinker.net/javaweb/upload-app.rar

Apache open-source software organizations with file upload two packages relating to:
l FileUpload package (commons-fileupload-X.jar): Packages file upload, download site at: http://commons.apache.org / FileUpload / .
Use the package description document URL is: http://commons.apache.org/fileupload/using.html .
 I / O package (commons-io-X.jar): Package is responsible for input and output, download site at: http://commons.apache.org/io/ .

JAR file should put two packages placed under helloapp / WEB-INF / lib directory. sourcecode / chapter05 / helloapp book supporting source code package / WEB-INF / lib directory has provided more than two JAR files. The main use of Servlet fileupload package of interfaces and classes to implement file upload, and fileupload package itself dependent on I / O packages. The following is a class diagram of FIG. 1-1 primary interfaces and classes fileupload package.

In the Servlet using the Apache open-source library for file uploads
A block diagram of the major classes of interfaces and classes 1-1 fileupload package of FIG.

1-2 shown below, for a text of "multipart / form-data" of HTTP request type, each sub-part of the package UploadFile form a composite body contained in the request portion is regarded as a FileItem object. FileItem subjects were divided into two types:
l formField: ordinary type form fields, text fields in a form and submit buttons are of this type.
 Non-formField: upload file type, file form field is this type that contains the file data.

In the Servlet using the Apache open-source library for file uploads
Each sub-portion 1-2 in FIG composite form as an object is FileItem

FileItemFactory is created FileItem object factory. DiskFileItemFactory classes and class were achieved DiskFileItem FileItemFactory FileItem interfaces and interfaces. DiskFileItem class represents FileItem-based hard drive, DiskFileItem class can save the client to upload data files to the hard disk. DiskFileItemFactory is created DiskFileItem object factory.
The following program code creates a DiskFileItemFactory object, and then set the write data to the hard disk size of the buffer used, as well as the temporary directory used. In fileupload own package implementation, in order to improve the efficiency of writing data to the hard disk, especially writing large amounts of data efficiently, fileupload packages can write data in the cache, and temporary storage of data to the temporary directory.

//创建一个基于硬盘的FileItem工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置向硬盘写数据时所用的缓冲区的大小,此处为4K
factory.setSizeThreshold(4*1024); 
//设置临时目录
factory.setRepository(new File(tempFilePath));

ServletFileUpload class file upload processor, which is associated with FileItemFactory. The following code creates a program ServletFileUpload object that is associated with a DiskFileItemFactory object. setSizeMax ServletFileUpload class () method is used to set the maximum allowed size of the uploaded file.

//创建一个文件上传处理器
ServletFileUpload upload = new ServletFileUpload(factory);
//设置允许上传的文件的最大尺寸,此处为4M
upload.setSizeMax(4*1024*1024); 

ServletFileUpload class parseRequest (HttpServletRequest req) method can resolve a composite form data HttpServletRequest object, returns object contains a set of List collection FileItem:

List<FileItem> items = upload.parseRequest(request);

After obtaining a set comprising FileItem List objects can traverse this set, it determines the type of each object FileItem, and then make the appropriate treatment.

for(FileItem item:items){  //遍历集合中的每个FileItem对象
  if(item.isFormField()) {
    processFormField(item,out); //处理普通的表单域
  }else{
    processUploadedFile(item,out); //处理上传文件
  }
}

The following routine 1-1 UploadServlet class to handle file uploads in upload.htm user page fileupload use package.

Routine 1-1 UploadServlet.java

package mypack;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;

public class UploadServlet extends HttpServlet {
  private String filePath; //存放上传文件的目录
  private String tempFilePath; //存放临时文件的目录

  public void init(ServletConfig config)throws ServletException {
    super.init(config);
    filePath=config.getInitParameter("filePath");
    tempFilePath=config.getInitParameter("tempFilePath");
    filePath=getServletContext().getRealPath(filePath);
    tempFilePath=getServletContext().getRealPath(tempFilePath);
  }
  public void doPost(HttpServletRequest request,
         HttpServletResponse response)
         throws ServletException, IOException {
    response.setContentType("text/plain");
    //向客户端发送响应正文
    PrintWriter out=response.getWriter(); 
    try{
      //创建一个基于硬盘的FileItem工厂
      DiskFileItemFactory factory = new DiskFileItemFactory();
      //设置向硬盘写数据时所用的缓冲区的大小,此处为4K
      factory.setSizeThreshold(4*1024); 
      //设置临时目录
      factory.setRepository(new File(tempFilePath));

      //创建一个文件上传处理器
      ServletFileUpload upload = new ServletFileUpload(factory);
      //设置允许上传的文件的最大尺寸,此处为4M
      upload.setSizeMax(4*1024*1024); 

      List<FileItem> items = upload.parseRequest(request);    

      for(FileItem item:items){
        if(item.isFormField()) {
          processFormField(item,out); //处理普通的表单域
        }else{
          processUploadedFile(item,out); //处理上传文件
        }
      }
      out.close();
    }catch(Exception e){
       throw new ServletException(e);
    }
  }

  private void processFormField(FileItem item,PrintWriter out){
    String name = item.getFieldName();
    String value = item.getString();
    out.println(name+":"+value+"\r\n");
  }

  private void processUploadedFile(FileItem item,
               PrintWriter out)throws Exception{
    String filename=item.getName();
    int index=filename.lastIndexOf("\\");
    filename=filename.substring(index+1,filename.length());
    long fileSize=item.getSize();

    if(filename.equals("") && fileSize==0)return;

    File uploadedFile = new File(filePath+"/"+filename);
    item.write(uploadedFile);
    out.println(filename+" is saved.");
    out.println("The size of " +filename+" is "+fileSize+"\r\n");
  }

UploadServlet web.xml file configuration code is as follows:

<servlet>
  <servlet-name>upload</servlet-name>
  <servlet-class>mypack.UploadServlet</servlet-class>
  <init-param>
    <param-name>filePath</param-name>
    <param-value>store</param-value>
  </init-param>
  <init-param>
    <param-name>tempFilePath</param-name>
    <param-value>temp</param-value>
  </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>upload</servlet-name>
  <url-pattern>/upload</url-pattern>
</servlet-mapping>

UploadServlet there are two initialization parameters: filePath parameter represents the directory for storing uploaded files UploadServlet; tempFilePath parameter represents the directory for temporary files fileupload package for storage.

The following routine upload.htm 1-2 defines a composite form for uploading files, it has a name for the "username" text field, there are two fields for specifying files to upload files.

Routine 1-2 upload.htm

<html>
<head>
<title>Upload</title>
</head>
<body >
  <form name="uploadForm" method="POST"
    enctype="MULTIPART/FORM-DATA"
    action="upload">
    <table>
      <tr>
       <td><div align="right">User Name:</div></td>
       <td><input type="text" name="username" size="30"/> </td>
      </tr>
      <tr>
       <td><div align="right">Upload File1:</div></td>
       <td><input type="file" name="file1" size="30"/> </td>
      </tr>
      <tr>
        <td><div align="right">Upload File2:</div></td>
        <td><input type="file" name="file2" size="30"/> </td>
      </tr>
      <tr>
        <td><input type="submit" name="submit" value="upload"></td>
        <td><input type="reset" name="reset" value="reset"></td>
      </tr>
    </table>
  </form>
</body>

</html>

From the browser to http: // localhost: 8080 / helloapp / upload.htm, HTML page shown in Figure 1-3 will appear.
In the Servlet using the Apache open-source library for file uploads
Figure 1-3 upload.htm page

For upload.htm FIG pages 1-3, there is provided in the form of data shown in FIG, and submit the form, UploadServlet will respond this request, the "FromClient.rar" and "FromClient.txt" files are saved to under helloapp / store directory, and returned to the client HTML page shown in FIG. 1-4.
In the Servlet using the Apache open-source library for file uploads
Figure 1-4 UploadServlet returned HTML page

UploadServlet call ServletFileUpload object setSizeMax (4 1024 1024) method, the maximum allowed file upload size is set to 4M. If you enter a file size exceeds 4M upload.htm page in Figure 1-3, then the following UploadServlet throws an exception when processing uploaded files:

org.apache.commons.fileupload.FileUploadBase
$SizeLimitExceededException: 
the request was rejected because its size (7859197) 
exceeds the configured maximum (4194304) 

In the Servlet using the Apache open-source library for file uploads

Guess you like

Origin blog.51cto.com/sunweiqin/2414513