packagecom.zj.sample;importjava.io.File;importjava.io.IOException;importjava.util.Iterator;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;/*** Servlet implementation class Upload*/@WebServlet("/Upload")public class Upload extendsHttpServlet {private static final long serialVersionUID = 1L;private String uploadPath = "D:\\temp"; //上传文件的目录
private String tempPath = "d:\\temp\\buffer\\"; //临时文件目录
File tempPathFile;/***@seeHttpServlet#HttpServlet()*/
publicUpload() {super();//TODO Auto-generated constructor stub
}/***@seeHttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {//TODO Auto-generated method stub
}/***@seeHttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/@SuppressWarnings("unchecked")public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsIOException, ServletException {try{//Create a factory for disk-based file items
DiskFileItemFactory factory = newDiskFileItemFactory();//Set factory constraints
factory.setSizeThreshold(4096); //设置缓冲区大小,这里是4kb
factory.setRepository(tempPathFile);//设置缓冲区目录//Create a new file upload handler
ServletFileUpload upload = newServletFileUpload(factory);//Set overall request size constraint
upload.setSizeMax(4194304); //设置最大文件尺寸,这里是4MB
List items = upload.parseRequest(request);//得到所有的文件
Iterator i =items.iterator();while(i.hasNext()) {
FileItem fi=(FileItem) i.next();
String fileName=fi.getName();if (fileName != null) {
File fullFile= newFile(fi.getName());
File savedFile= newFile(uploadPath, fullFile.getName());
fi.write(savedFile);
}
}
System.out.print("upload succeed");
}catch(Exception e) {//可以跳转出错页面
e.printStackTrace();
}
}public void init() throwsServletException {
File uploadFile= newFile(uploadPath);if (!uploadFile.exists()) {
uploadFile.mkdirs();
}
File tempPathFile= newFile(tempPath);if (!tempPathFile.exists()) {
tempPathFile.mkdirs();
}
}
}