FileUpload上传组件依赖commons-io组件的支持,上传文件依赖DiskFileItemFactory、ServletFileUpload、FileItem,parseRequest(request)方法将request请求中封装的所有信息(包含非文件上传控件)封装至List<FileItem>中。
<%@ page contentType="text/html" pageEncoding="GBK"%> <%@ page import="java.util.*"%> <%@ page import="java.io.*"%> <%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> <%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> <%@ page import="org.apache.commons.fileupload.FileItem"%> <%@ page import="org.xiong.Rand.RandName"%> <% DiskFileItemFactory dff=new DiskFileItemFactory(); dff.setRepository(new File(this.getServletContext().getRealPath("/")+"FileUploadDemo"+File.separator+"tempUpload")); ServletFileUpload sfu= new ServletFileUpload(dff); sfu.setFileSizeMax(10*1024*1024); List<FileItem> allFileItems=sfu.parseRequest(request); Iterator<FileItem> iterItems=allFileItems.iterator(); while(iterItems.hasNext()) { FileItem fitem=iterItems.next(); if(!fitem.isFormField()) { InputStream srcStream=fitem.getInputStream(); OutputStream outStream=null; String oriFileName=fitem.getName(); String extName=oriFileName.substring(oriFileName.lastIndexOf(".")); RandName newName=new RandName(request.getRemoteAddr()); String completeNewName=newName.getRandName()+extName; try { outStream=new FileOutputStream(new File(this.getServletContext().getRealPath("/")+"FileUploadDemo"+File.separator+"upload"+File.separator+completeNewName)); int temp=0; byte[] content=new byte[1024]; while((temp=srcStream.read(content))!=-1) { outStream.write(content); } } catch(Exception ex) { ex.printStackTrace(); } finally { try { outStream.close(); srcStream.close(); } catch(Exception ex) { ex.printStackTrace(); } } } else { String fieldName=fitem.getFieldName(); String fieldValue=fitem.getString(); %> <h1><%=fieldName%>========<%=fieldValue%></h1> <% } } %>
Struts中集成了FileUpload组件(以及commons-io),