在这里,我们将学习如何使用Servlet处理文件上传到服务器。要将文件上传到服务器,html文件中表单的方法必须指定为:post
,并且enctype
必须是multipart/form-data
。 例如:
<form action="go" method="post" enctype="multipart/form-data">
注意:
method
和enctype
指定的值不正确,文件将无法正常上传和接收。
在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:\temp
和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.");
}
}
}