package com.upload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
public class UploadTest extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uploadPath = getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上传成功!");
}
}
}
} catch (Exception ex) {
request.setAttribute("message", "错误信息: " + ex.getMessage());
}
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
==============================================================================
上传jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
<style type="text/css">
p{
text-align: center;
}
</style>
</head>
<body>
<p>
_ooOoo_ <br />
o8888888o <br />
88" . "88 <br />
(| -_- |) <br />
O\ = /O <br />
____/`---'\____ <br />
.' \\| |// `. <br />
/ \\||| : |||// \ <br />
/ _||||| -:- |||||- \ <br />
| | \\\ - /// | | <br />
| \_| ''\---/'' | | <br />
\ .-\__ `-` ___/-. / <br />
___`. .' /--.--\ `. . __ <br />
."" '< `.___\_<|>_/___.' >'"". <br />
| | : `- \`.;`\ _ /`;.`/ - ` : | | <br />
\ \ `-. \_ __\ /__ _/ .-` / / <br />
======`-.____`-.___\_____/___.-`____.-'====== <br />
`=---=' <br />
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <br />
佛祖保佑 永无BUG <br />
<br />
写字楼里写字间,写字间里程序员; <br />
程序人员写程序,又拿程序换酒钱。 <br />
酒醒只在网上坐,酒醉还来网下眠; <br />
酒醉酒醒日复日,网上网下年复年。 <br />
但愿老死电脑间,不愿鞠躬老板前; <br />
奔驰宝马贵者趣,公交自行程序员。 <br />
别人笑我忒疯癫,我笑自己命太贱; <br />
不见满街漂亮妹,哪个归得程序员? <br />
<br />
</p>
<h1>文件上传</h1>
<form method="post" action="servlet/UploadTest" enctype="multipart/form-data">
选择一个文件:
<input type="file" name="uploadFile" />
<br/><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
==============================================================================
提示jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
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%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传结果</title>
</head>
<body>
<center>
<h2>${message}</h2>
</center>
</body>
</html>
==============================================================================
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>UploadTest</servlet-name>
<servlet-class>com.upload.UploadTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadTest</servlet-name>
<url-pattern>/servlet/UploadTest</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
==============================================================================
==============================================================================
==============================================================================