新建类 UploadServlet
package org.action;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@SuppressWarnings("unchecked")
public class UploadServlet extends HttpServlet{
private static final long serialVersionUID = 1L ;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp) ;
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory() ;
factory.setSizeThreshold( 8192 ) ;
String tempPath = request.getSession().getServletContext().getRealPath( "/")
+ "/upload" ;
File file = new File( tempPath ) ;
if(!file.isDirectory()){
file.mkdirs();
}
factory.setRepository( file ) ;
ServletFileUpload upload = new ServletFileUpload( factory ) ;
List<FileItem> items;
try {
items = upload.parseRequest(request);
Iterator<FileItem> itr = items.iterator();
while (itr.hasNext()) {// 依次处理每个 form field
FileItem item = (FileItem) itr.next();
if(!item.isFormField()){ /* 判断是否为表单控件(非File控件),如果不是表单控件,则上传此文件 */
File savedFile = new File( tempPath , item.getName() ) ;
item.write(savedFile) ;
}else{/* 如果是表单控件,则保存其值*/
System.out.println( item.getFieldName() + "-->" + item.getString() ) ;
}
}
}catch (Exception e){
e.printStackTrace() ;
}
}
}
在web.xml 中配置:
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>org.action.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/upload</url-pattern>
</servlet-mapping>
页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<form action="<%=basePath %>upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input value="name" name="name" type="text" />
<input type="submit"/>
</form>
</body>
</html>
依赖的jar包,commons-fileupload-1.1.jar 和 commons-io-1.1.jar