Servlet上傳文件

在這裏,我們將學習如何使用Servlet處理文件上傳到服務器。要將文件上傳到服務器,html文件中表單的方法必須指定爲:post,並且enctype必須是multipart/form-data。 例如:

<form action="go" method="post" enctype="multipart/form-data">

注意: methodenctype指定的值不正確,文件將無法正常上傳和接收。

在servlet中將文件上傳到服務器的示例

要將文件上傳到服務器,有多種方法可以完成這個工作。但是,將使用由oreilly提供的MultipartRequest類。對於使用此類,必須有cos.jar文件。如果下載這個例子的項目代碼,我們已經在項目目錄WEB-INF/lib附帶了cos.jar文件。

打開Eclipse,創建一個動態Web項目:UploadFileHandle,其完整的目錄結構如下所示 -

Servlet上傳文件

以下是這個項目中的幾個主要的代碼文件。

文件:index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上傳示例</title>
</head>
<body>
    <div style="margin: auto; text-align: center">
        <form action="upload" method="post" enctype="multipart/form-data">
            選擇文件:<input type="file" name="fname" /><input type="submit"
                value="上傳" />
        </form>
    </div>
</body>
</html>

文件:UploadServlet.java

package com.yiibai;

import java.io.*;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import com.oreilly.servlet.MultipartRequest;

public class UploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        // String dir = System.getProperty("user.dir")+"/uploads";
        String dir = request.getSession().getServletContext().getRealPath("");
        System.out.println("Save to path: " + dir);
        MultipartRequest mr = new MultipartRequest(request, dir);
        // 傳回所有文件輸入類型的名稱
        Enumeration files = mr.getFileNames();
        String fileName = "";
        String filePath = "";
        while (files.hasMoreElements()) {
            fileName = (String) files.nextElement();
            System.out.println("FileName = " + fileName);
            // 用此方法得到上傳文件的真正的文件名,這裏的fileName指文件輸入類型的名稱
            filePath = mr.getFilesystemName(fileName);
            System.out.println("FilePath = " + filePath);
            // 此方法得到一個文件對象,代表儲存在服務器上的fileName文件
            File f = mr.getFile(fileName);
            if (null == f) {
                throw new ServletException("file is not exist");
            }
        }
        out.print("successfully uploaded");
        out.close();
    }
}

注意:
MultipartRequest類構造函數中傳遞了兩個參數,第一個是HttpServletRequest對象,第二個是String對象(指定存儲目錄位置)。在這裏假設在當前項目文件下存儲上傳的文件。

文件:web.xml

此配置文件提供有關servlet的信息。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>UploadFileHandle</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.yiibai.UploadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>
</web-app>

在編寫上面代碼後,部署此Web應用程序(在項目名稱上點擊右鍵->」Run On Server…」),打開瀏覽器訪問URL: http://localhost:8080/UploadHandle/ ,如果沒有錯誤,應該會看到以下結果 -

Servlet上傳文件

在選擇好要上傳文件後,提交上傳,打開項目部署的目錄,將會看到文件已經上傳成功 -

Servlet上傳文件

同時在終端上也輸出以下有關文件的信息:

Save to path: F:\worksp\servlet\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\UploadFileHandle\
FileName = fname
FilePath = 0171015223409.png

上傳文件處理方法二

以下是UploadServlet的源代碼,可以一次處理多個文件上傳。在進行之前,請確保以下內容準備完成 -

  • 以下示例使用上傳組件:FileUpload,因此請確保類路徑中有最新版本的commons-fileupload.x.x.jar文件。可以從 http://commons.apache.org/fileupload/ 下載。
  • FileUpload上傳組件取決於Commons IO,因此請確保類路徑中有最新版本的commons-io-x.x.jar文件,可以從 http://commons.apache.org/io/ 下載。
  • 在測試以下示例之前,應該上傳的文件的大小設置爲小於maxFileSize,否則將不會上傳文件。

確保提前創建目錄C:\tempwebapps\data,如何實現請參考以下代碼 -

// Import required java libraries
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {

   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath = getServletContext().getInitParameter("file-upload"); 
   }

   public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {

      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );

      if( !isMultipart ) {
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>"); 
         out.println("</body>");
         out.println("</html>");
         return;
      }

      DiskFileItemFactory factory = new DiskFileItemFactory();

      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);

      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);

      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try { 
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");  
         out.println("</head>");
         out.println("<body>");

         while ( i.hasNext () ) {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) {
               // Get the uploaded file parameters
               String fieldName = fi.getFieldName();
               String fileName = fi.getName();
               String contentType = fi.getContentType();
               boolean isInMemory = fi.isInMemory();
               long sizeInBytes = fi.getSize();

               // Write the file
               if( fileName.lastIndexOf("\\") >= 0 ) {
                  file = new File( filePath + fileName.substring( fileName.lastIndexOf("\\"))) ;
               } else {
                  file = new File( filePath + fileName.substring(fileName.lastIndexOf("\\")+1)) ;
               }
               fi.write( file ) ;
               out.println("Uploaded Filename: " + fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
         } catch(Exception ex) {
            System.out.println(ex);
         }
      }

      public void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, java.io.IOException {

         throw new ServletException("GET method used with " +
            getClass( ).getName( )+": POST method required.");
      }
   }
}