本示例使用该Apache Commons FileUpload库创建一个用于上传文件的简单应用程序。该程序分为两部分,一种是使用JSP的表单,另一种是用于处理上传过程的servlet。要运行该示例,您需要下载Commons FileUpload,并且Commons IO获取最新的稳定版本。
第一步是创建上传表单。该表单包含两个字段,用于选择要上传的文件和一个提交按钮。该表单应具有一个enctype属性,值是multipart/form-data。我们使用post方法,提交过程由属性中FileUploadDemoServlet定义的处理action。
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>File Upload</title> </head> <body> <h1>File Upload Form</h1> <hr/> <fieldset> <legend>Upload File</legend> <form action="/uploadservlet" method="post" enctype="multipart/form-data"> <label for="filename_1">File: </label> <input id="filename_1" type="file" name="filename_1" size="50"/><br/> <label for="filename_2">File: </label> <input id="filename_2" type="file" name="filename_2" size="50"/><br/> <br/> <input type="submit" value="Upload File"/> </form> </fieldset> </body> </html>
第二步是创建servlet。该doPost方法检查请求是否包含多部分内容。之后,我们创建一个FileItemFactory,在本示例中,我们使用DiskFileItemFactory的默认工厂FileItem。此工厂FileItem根据其内容大小创建一个实例并将其存储在内存或磁盘上的临时文件中。
可以ServletFileUpload处理我们在上述表单中使用multipart / mixed编码类型发送的多个文件上传。数据的存储过程由FileItemFactory传递给ServletFileUpload类的对象确定。
下一步是multipart/form-data通过调用ServletFileUpload.parseRequest(HttpServletRequest request)方法来解析流。解析过程返回的列表FileItem。之后,我们在列表上进行迭代,并检查是否FileItem代表上传的文件或简单的表单字段。如果它代表上传的文件,我们会将FileItem内容写入文件。
所以这里是FileUploadDemoServlet。
package org.nhooo.example.commons.fileupload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; public class FileUploadDemoServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } }
最后,我们需要注册servlet并在应用程序web.xml文件中创建servlet映射。以下是的内容web.xml。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>FileUploadDemoServlet</servlet-name> <servlet-class>org.nhooo.example.commons.fileupload.FileUploadDemoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileUploadDemoServlet</servlet-name> <url-pattern>/uploadservlet</url-pattern> </servlet-mapping> </web-app>
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=commons-fileupload/commons-fileupload/1.4/commons-fileupload-1.4.jar --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>