public void doPost(HttpServletRequest req, HttpServletResponse res) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File("/tmp")); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown upload.setSizeMax(1000000); List fileItems = upload.parseRequest(req); // assume we know there are two files. The first file is a small // text file, the second is unknown and is written to a file on // the server Iterator i = fileItems.iterator(); String comment = ((FileItem)i.next()).getString(); FileItem fi = (FileItem)i.next(); // filename on the client String fileName = fi.getName(); // save comment and filename to database ... // write the file fi.write(new File("/www/uploads/", fileName)); }
以上代码为apache官网的一段commons-fileupload的demo。其中主要分为两个部分
1、创建DiskFileItemFactory
2、创建SerletFileUpload
(1)DiskFileItemFactory实现了FileItemFactory接口createItem,在里面指定了默认的阀值。同时声明一个FileCleaningTracker去跟踪是否超过阀值。