可见:FileItemSteam(servletFileUpload.getItemIterator(httpServletRequest))速度要快于FileItem(servletFileUpload.parseRequest(request))速度。且一般情况下,FileItemSteam不产生临时文件:
package cn.itcast.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Scanner; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; /** * FileItemStream示例 * @author <a href="mailto:wj@itcast.cn">王健</a> * @version 1.0 2012-3-15 */ public class Upload3Servlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { long start = System.currentTimeMillis(); String path = getServletContext().getRealPath("/imgs"); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 8);// 设置8k的缓存空间 factory.setRepository(new File("d:/a")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");// 设置文件名处理中文编码 try { FileItemIterator fii = upload.getItemIterator(request);// 使用遍历类 while (fii.hasNext()) { FileItemStream fis = fii.next(); if (fis.isFormField()) {//FileItemStream同样使用OpenStream获取普通表单的值 InputStreamReader in = new InputStreamReader(fis.openStream(),"UTF-8"); Scanner sc = new Scanner(in); StringBuffer sb = new StringBuffer(); if(sc.hasNextLine()){ sb.append(sc.nextLine()); } System.err.println("Desc:"+sb.toString()); } else { String fileName = fis.getName(); fileName = fileName .substring(fileName.lastIndexOf("\") + 1); System.err.println("文件名为:" + fileName); InputStream in = fis.openStream(); FileUtils.copyInputStreamToFile(in, new File(path+"/"+fileName)); } } } catch (FileUploadException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.err.println("用时:"+(end-start)); } }
转自: