JSP - 文件上传

在本章中,我们将讨论JSP中的文件上传. JSP可以与HTML表单标记一起使用,以允许用户将文件上载到服务器.上传的文件可以是文本文件,也可以是二进制文件或图像文件,也可以是任何文档.

创建文件上载表单

现在就让我们吧了解如何创建文件上载表单.以下HTML代码创建了一个上传器表单.以下是需要注意的重要事项:

  • 表单方法属性应该是设置为 POST 方法并且无法使用GET方法.

  • 表单 enctype 属性应该是设置为 multipart/form-data .

  • 表单 action 属性应设置为JSP将在后端服务器上处理文件上载的文件.以下示例使用 uploadFile.jsp 程序文件上传文件.

  • 要上传单个文件,您应该使用单个< input .../> 标记,其属性为 type ="file".要允许多个文件上载,请包含多个具有不同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:\ temp c:\ 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表单上传文件.当您尝试 http://localhost:8080/UploadFile.htm 时,它将显示以下结果.这将帮助您从本地计算机上传任何文件.

File Upload:
Select a file to upload:

如果你的JSP脚本工作正常,你的文件应该上传到 c:\ apache-tomcat5.5.29\webapps\data\ 目录.