工具: myeclipse 6.5
1. 新建项目 fileUpload
在 com.shiryu 包下新建 Servlet : FileUpload.java
package com.shiryu;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.*;
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;
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = -5361390019270693076L;
// 文件上传路径
private String uploadPath;
// 临时文件路径
private File tempPath;
public FileUpload() {
uploadPath = "D://test//";
tempPath = new File("C://windows//temp//");
}
public void init() throws ServletException {
if (!(new File(uploadPath)).isDirectory())
(new File(uploadPath)).mkdir();
if (!tempPath.isDirectory())
tempPath.mkdir();
}
public void destroy() {
super.destroy();
}
@SuppressWarnings({ "unchecked", "unchecked" })
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(tempPath);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(0xf4240L);
List fileItems = null;
try {
fileItems = upload.parseRequest(req);
Iterator iter = fileItems.iterator();
String regExp = ".+(.+)$";
// 限制上传文件的格式
String errorType[] = { ".exe", ".com", ".cgi", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if (name != null && !name.equals("") || size != 0L) {
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++)
if (m.group(1).endsWith(errorType[temp]))
throw new IOException(name + ": wrong type");
try {
item.write(new File(uploadPath, m.group(1)));
} catch (Exception e) {
out.println(e);
}
} else {
throw new IOException("fail to upload");
}
}
}
}
} catch (IOException e) {
out.println("222" + e);
} catch (FileUploadException e1) {
e1.printStackTrace();
}
}
}
2. 配置 web.xml 文件的内容
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>upload_3</servlet-name>
<servlet-class>com.shiryu.FileUpload</servlet-class>
<init-param>
<param-name>upload</param-name>
<param-value>/WEB-INF/upload</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>upload_3</servlet-name>
<url-pattern>/upload_3</url-pattern>
</servlet-mapping>
</web-app>
3. 前台 upload_3.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title>
</head>
<body>
<form action="upload_3" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
<form name="uploadform" method="POST" action="upload_3" ENCTYPE="multipart/form-data">
<table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF">
<tr>
<td width="100%" colspan="2">
file1:<input name="x" size="40" type="file">
</td>
</tr>
<tr>
<td width="100%" colspan="2">
file2:<input name="y" size="40" type="file">
</td>
</tr>
<tr>
<td width="100%" colspan="2">
file3:<input name="z" size="40" type="file">
</td>
</tr>
</table>
<br />
<table>
<tr>
<td align="center">
<input name="upload" type="submit" value="sure" />
</td>
</tr>
</table>
</form>
</body>
</html>