准备工作:
相关文件下载:
1.commons-io-1.2.jar: http://apache.justdn.org/jakarta/commons/io/binaries/commons-io-1.2.zip
2.commons-fileupload-1.1.1.jar:ftp://justdn.org/apache/jakarta/commons/fileupload/binaries/commons-fileupload-1.1.1.zip
servlet代码:
/**
* Class Description:
*/
public class UploadFileServlet extends HttpServlet {
private String uploadPath = "C:\\upload\\"; // 上传文件的目录
private String tempPath = "C:\\upload\\tmp\\"; // 临时文件目录
static String filename = "0";
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
{
String uploadPath = "C:/temp2/"; // 用于存放上传文件的目录
String tempPath = "C:/temp"; // 用于存放临时文件的目录
boolean isMultipart = FileUpload.isMultipartContent(request);
if (!isMultipart) {
return;
}
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);
factory.setRepository(new File(tempPath));
// Create a new file upload handler
FileUpload upload = new FileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(1263509131 * 1024);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
name = name.substring(
name.lastIndexOf(File.separator) + 1, name
.length());
filename = (Integer.parseInt(filename) + 1) + "";
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
item.write(new File(uploadPath + filename));// 这里的路径你可以改成你感兴趣的地方
}
}
} catch (Exception e) {
// 可以跳转出错页面
e.printStackTrace();
}
response.sendRedirect("index.html");
}
}
}
web.xml代码
<servlet>
<servlet-name>Upload</servlet-name>
<servlet-class>
UploadFileServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/fileupload</url-pattern>
</servlet-mapping>
html页面:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY>
<form action="fileupload" method="post"
enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
</BODY>
</HTML>
将上面部署在一个web应用中就OK!