Apache 官网使用指南:http://commons.apache.org/fileupload/using.html
Apache Common fileUpload API 详解:http://www.blogjava.net/gembin/archive/2008/05/08/199240.html
JSP页面:
<form id="form1" name="form1" action="formProcess" method="post" enctype="multipart/form-data">
File Name: <input type="text" name="name" value="<%=request.getAttribute("line")%>" /> <br />
File: <input type="file" name="myFile" /> <br />
<input type="submit" value="Process" />
</form>
Servlet 处理文件上传:
public class FormProcess extends HttpServlet {
String uploadPath = "D:\\test";
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String line = null;
String fileName = null;
File fullFile = null;
try {
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
// Apache文件上传组件在解析和处理上传数据中的每个字段内容时,需要临时保存解析出的数据。因为Java虚拟机默认可以使用的内存空间是有
// 限的(笔者测试不大于100M),超出限制时将会发生“java.lang.OutOfMemoryError”错误
factory.setSizeThreshold(4096); // your max memory
// size.设置最多只允许在内存中存储的数据,单位:字节
// 设置setSizeThreshold方法中提到的临时文件的存放目录,这里要求使用绝对路径
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
// factory.setRepository(new File(uploadPath));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint.设置允许用户上传文件大小,单位:字节
upload.setSizeMax(8194304);
// Parse the request
List /* FileItem */items = null;
items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
/* processFormField(item); */
// Process a regular form field
String name = item.getFieldName();
line = item.getString("UTF-8");
System.out.println(name + ": " + line);
} else {
/* processUploadedFile(item); */
String fieldName = item.getFieldName();
fileName = item.getName();
fullFile = new File(fileName);
File uploadedFile = new File(uploadPath, fullFile.getName());
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("line", line);
request.setAttribute("fileName", fullFile.getCanonicalPath());
this.getServletConfig().getServletContext()
.getRequestDispatcher("/index.jsp").forward(request, response);
}
@Override
public void init() throws ServletException {
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
}
}