鍍金池/ 教程/ Java/ 文件上傳
發(fā)送電子郵件
調(diào)試
異常處理
自動(dòng)刷新頁面
處理日期
實(shí)例
生命周期
數(shù)據(jù)庫訪問
國際化
會(huì)話跟蹤
環(huán)境設(shè)置
客戶端 HTTP 請(qǐng)求
文件上傳
頁面重定向
服務(wù)器 HTTP 響應(yīng)
編寫過濾器
表單數(shù)據(jù)
HTTP 狀態(tài)碼
Cookies 處理
概述
點(diǎn)擊計(jì)數(shù)器

文件上傳

Servlet 可以與 HTML form 標(biāo)簽一起使用允許用戶將文件上傳到服務(wù)器。上傳的文件可以是文本文件或圖像文件或任何文檔。

創(chuàng)建一個(gè)文件上傳表單

下述 HTML 代碼創(chuàng)建了一個(gè)文件上傳表單。以下是需要注意的幾點(diǎn):

  • 表單 method 屬性應(yīng)該設(shè)置為 POST 方法且不能使用 GET 方法。

  • 表單 enctype 屬性應(yīng)該設(shè)置為 multipart/form-data.

  • 表單 action 屬性應(yīng)該設(shè)置為 servlet 文件,能夠在后端服務(wù)器處理文件上傳。下面的例子是使用 UploadServlet servlet 來上傳文件的。

  • 要上傳單個(gè)文件,你應(yīng)該使用單個(gè)帶有屬性 type=“file” 的 <input .../> 標(biāo)簽。為了允許多個(gè)文件上傳,要包含多個(gè)帶有 name 屬性不同值的輸入標(biāo)簽。瀏覽器將把一個(gè)瀏覽按鈕和每個(gè)輸入標(biāo)簽關(guān)聯(lián)起來。
 
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

這將顯示如下所示的結(jié)果,允許從本地計(jì)算機(jī)中選擇一個(gè)文件,當(dāng)用戶點(diǎn)擊“上傳文件”時(shí),表單會(huì)和選擇的文件一起提交:

 
File Upload: 
Select a file to upload: 


NOTE: This is just dummy form and would not work.

編寫后臺(tái) Servlet

以下是 servlet UploadServlet,會(huì)接受上傳的文件并把它儲(chǔ)存在目錄 <Tomcat-installation-directory>/webapps/data 中。使用外部配置,如 web.xml 中的 context-param 元素,這個(gè)目錄名也可以被添加,如下所示:

<web-app>
....
<context-param> 
    <description>Location to store uploaded file</description> 
    <param-name>file-upload</param-name> 
    <param-value>
         c:\apache-tomcat-5.5.29\webapps\data\
     </param-value> 
</context-param>
....
</web-app>

以下是 UploadServlet 的源代碼,可以一次處理多個(gè)文件的上傳。在繼續(xù)操作之前,請(qǐng)確認(rèn)下列各項(xiàng):

  • 下述例子依賴于 FileUpload,所以一定要確保在你的 classpath 中有最新版本的 commons-fileupload.x.x.jar 文件。你可以從 http://commons.apache.org/fileupload/ 中下載。

  • FileUpload 依賴于 Commons IO,所以一定要確保在你的 classpath 中有最新版本的 commons-io-x.x.jar 文件。可以從 http://commons.apache.org/io/ 中下載。

  • 在測(cè)試下面實(shí)例時(shí),你上傳的文件大小不能大于 maxFileSize,否則文件將無法上傳。

  • 請(qǐng)確保已經(jīng)提前創(chuàng)建好目錄 c:\temp and c:\apache-tomcat-5.5.29\webapps\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.");
   } 
}

編譯和運(yùn)行 Servlet

編譯上述 servlet UploadServlet 并在 web.xml 文件中創(chuàng)建所需的條目,如下所示:

<servlet>
   <servlet-name>UploadServlet</servlet-name>
   <servlet-class>UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>UploadServlet</servlet-name>
   <url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>

現(xiàn)在嘗試使用上面創(chuàng)建的 HTML 表單來上傳文件。當(dāng)你訪問 http://localhost:8080/UploadFile.htm 時(shí),它會(huì)顯示如下所示的結(jié)果,這將有助于你從本地計(jì)算機(jī)中上傳任何文件。

 
File Upload: 

Select a file to upload:

如果你的 servelt 腳本能正常工作,那么你的文件會(huì)被上傳到 c:\apache-tomcat-5.5.29\webapps\data\ 目錄中。

上一篇:Cookies 處理下一篇:HTTP 狀態(tài)碼