JSP - 檔案上傳



本章將討論JSP中的檔案上傳。JSP可以與HTML表單標籤一起使用,允許使用者將檔案上傳到伺服器。上傳的檔案可以是文字檔案、二進位制檔案、影像檔案或任何文件。

建立檔案上傳表單

現在讓我們瞭解如何建立檔案上傳表單。以下HTML程式碼建立了一個上傳表單。以下是需要注意的重要事項:

  • 表單的method屬性應設定為POST方法,不能使用GET方法。

  • 表單的enctype屬性應設定為multipart/form-data

  • 表單的action屬性應設定為一個JSP檔案,該檔案將在後端伺服器處理檔案上傳。以下示例使用uploadFile.jsp程式檔案上傳檔案。

  • 要上傳單個檔案,應使用單個<input .../>標籤,其屬性type = "file"。要允許上傳多個檔案,請包含多個input標籤,併為name屬性使用不同的值。瀏覽器會為每個標籤關聯一個“瀏覽”按鈕。

<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>

這將顯示以下結果。您現在可以選擇本地PC上的檔案,當用戶單擊“上傳檔案”時,表單將與所選檔案一起提交:

File Upload

Select a file to upload −



注意 - 以上表單只是一個示例表單,無法直接執行,您應該在自己的機器上嘗試以上程式碼才能使其工作。

編寫後端JSP指令碼

現在讓我們定義一個上傳檔案將儲存的位置。您可以在程式中硬編碼此位置,也可以使用外部配置(例如web.xml中的context-param元素)新增此目錄名稱,如下所示:

<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>

以下是UploadFile.jsp的原始碼。這可以一次處理多個檔案的上傳。在繼續上傳檔案之前,讓我們考慮以下幾點。

  • 以下示例依賴於FileUpload;確保您的類路徑中包含最新版本的commons-fileupload.x.x.jar檔案。您可以從https://commons.apache.org/fileupload/下載。

  • FileUpload依賴於Commons IO;確保您的類路徑中包含最新版本的commons-io-x.x.jar檔案。您可以從https://commons.apache.org/io/下載。

  • 測試以下示例時,您應該上傳大小小於maxFileSize的檔案,否則檔案將不會上傳。

  • 確保您已提前建立目錄c:\tempc:\apache-tomcat5.5.29\webapps\data

<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>

<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
   String filePath = context.getInitParameter("file-upload");

   // Verify the content type
   String contentType = request.getContentType();
   
   if ((contentType.indexOf("multipart/form-data") >= 0)) {
      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>JSP File 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();
               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: " + filePath + 
               fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      } catch(Exception ex) {
         System.out.println(ex);
      }
   } else {
      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>");
   }
%>

現在嘗試使用上面建立的HTML表單上傳檔案。當您嘗試https://:8080/UploadFile.htm時,它將顯示以下結果。這將幫助您從本地計算機上傳任何檔案。

File Upload

Select a file to upload −


如果您的JSP指令碼執行正常,您的檔案應該上傳到c:\apache-tomcat5.5.29\webapps\data\目錄。

廣告