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,其完整的目錄結構如下所示 -

以下是這個專案中的幾個主要的程式碼檔案。

檔案: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/ ,如果沒有錯誤,應該會看到以下結果 -

在選擇好要上傳檔案後,提交上傳,開啟專案部署的目錄,將會看到檔案已經上傳成功 -

同時在終端上也輸出以下有關檔案的資訊:

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.");
      }
   }
}