上传原理:
回顾:
之前不使用框架,导入commons-fileupload.jar和commons-io.jar
首先进行解析,将request对应参数转为File对象:
使用factory:
request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); //设置上传工厂的限制 factory.setSizeThreshold(1024 * 1024 * 20); factory.setRepository(new File(request.getRealPath("/"))); //创建一个上传文件的ServletFileUpload对象 ServletFileUpload upload = new ServletFileUpload(factory); //设置最大的上传限制 upload.setSizeMax(1024 * 1024 * 20); //处理HTTP请求,items是所有的表单项 List items = upload.parseRequest(request); //遍历所有的表单项 for(Iterator it = items.iterator();it.hasNext();){ FileItem item = (FileItem) it.next(); if(item.isFormField()){ String name = item.getFieldName(); String value = item.getString("GBK"); out.println("表单域的name=value对为:" + name + "=" + value); }else{ ....... } }
不使用factory:
DiskFileUpload diskFileUpload = new DiskFileUpload(); try{ List<FileItem> list = diskFileUpload.parseRequest(request); out.println("遍历所有的FileItem...<br/>"); for(FileItem fileItem : list){ if(fileItem.isFormField()){ if("description1".equals(fileItem.getFieldName())){ out.println("遍历到description1 ... <br/>"); description1 = new String(fileItem.getString().getBytes(),"UTF-8"); } if("description2".equals(fileItem.getFieldName())){ out.println("遍历到description2 ... <br/>"); description2 = new String(fileItem.getString().getBytes(),"UTF-8"); } }else{
......
}
}
}catch(Exception e){
......
}
然后,获取对应参数构建InputStream和OutputStream,进行IO读写操作
//取得文件域的表单域名 String fieldName = item.getFieldName(); //取得文件名 String fileName = item.getName(); //取得文件类型 String contentType = item.getContentType(); out.println("表单域的name=value对为:" + fieldName + "=" + fileName); //以原文件名作为新的文件名 FileOutputStream fos = new FileOutputStream(request.getRealPath("/") + fileName); //如果上传文件域对应文件的内容已经在内存中 if(item.isInMemory()){ fos.write(item.get()); }else{ //获取上传文件内容的输入流 InputStream is = item.getInputStream(); byte[] buffer = new byte[1024]; int len; //读取上传文件的内容,并将其写入服务器的文件中 while((len = is.read(buffer)) > 0){ fos.write(buffer,0,len); } //关闭输入流和输出流 is.close(); fos.close(); }
struts2的文件上传与之前的文件上传有什么区别呢?
其实原理都是一样的。不过是struts2将前面解析file控件传递过来的内容解析自动解析成了对应的对象,并且自动赋值给了action内的对应对象。
>该解析操作封装在一个默认的拦截器中。fileUpload拦截器
<interceptor-ref name="fileUpload"/>
该拦截器有三个参数:
maxmumSize :最大上传字节,默认为2M
allowedTypes:允许上传的类型,用逗号分隔,例如:text/html
allowedExtensions:允许上传文件的后缀名,用逗号分隔,例如:.html
>自动赋值给action中对应属性,两个要求:
调用默认拦截器组:<interceptor-ref name="defaultStack" />
jsp和action中的属性名要一致,举个例子说明吧:
jsp中: <s:file name="upload" label="File"/> action中属性: private File upload; private String uploadFileName; private String uploadContentType; 对应getter和setter方法
单个文件上传:
package com.upload; import java.io.*; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ private File file; private String fileFileName; private String filecontentType; public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFilecontentType() { return filecontentType; } public void setFilecontentType(String filecontentType) { this.filecontentType = filecontentType; } public String execute(){ InputStream is=null; OutputStream os=null; try { is = new FileInputStream(file); String path=ServletActionContext.getServletContext().getRealPath("upload"); File newFile=new File(path,this.getFileFileName()); os=new FileOutputStream(newFile); byte[] b=new byte[1024]; int len=0; while((len=is.read(b))!=-1){ os.write(b, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(is!=null)is.close(); if(os!=null)os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } } <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:form action="upload" method="post" enctype="multipart/form-data" namespace="/"> <s:file name="file"></s:file> <s:submit label="OK"></s:submit> </s:form> </body> </html> <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:iterator var="t" value="#request.fileName"> <s:property value="t"/> </s:iterator> <!-- <s:property value="#request.fileFileName"/> <br/> --> <!-- 该对象既被存放在值栈中又被存放在request对象内 --> <!--<s:property value="fileFileName"/> --> </body> </html> <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="default" extends="struts-default" namespace="/"> <action name="upload" class="com.upload.UploadAction"> <interceptor-ref name="fileUpload"/> <interceptor-ref name="defaultStack"></interceptor-ref> <result>/jsp/upload/success.jsp</result> </action> <action name="fileupload" class="com.upload.FilesUploadAction"> <interceptor-ref name="fileUpload"/> <interceptor-ref name="defaultStack"></interceptor-ref> <result>/jsp/upload/success.jsp</result> </action> </package> </struts>
上传多个文件:
struts.xml和success.xml共用 package com.upload; import java.io.*; import java.util.*; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class FilesUploadAction extends ActionSupport { private List<File> file; private List<String> fileFileName; private List<String> fileContentType; public List<File> getFile() { return file; } public void setFile(List<File> file) { this.file = file; } public List<String> getFileFileName() { return fileFileName; } public void setFileFileName(List<String> fileFileName) { this.fileFileName = fileFileName; } public List<String> getFileContentType() { return fileContentType; } public void setFileContentType(List<String> fileContentType) { this.fileContentType = fileContentType; } public String execute(){ String root=ServletActionContext.getServletContext().getRealPath("/")+"/upload"; List<File> fy=file; InputStream is=null; OutputStream os=null; for(int i=0;i<fy.size();i++){ try { byte[] buffer=new byte[1024]; is=new FileInputStream(file.get(i)); File newFile=new File(root,fileFileName.get(i)); os=new FileOutputStream(newFile); int len=0; while((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ is=null; os=null; } } return "success"; } } <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'login.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:form action="fileupload" method="post" enctype="multipart/form-data" namespace="/"> <s:file name="file"></s:file><br/> <s:file name="file"></s:file><br/> <s:file name="file"></s:file> <s:submit label="OK"></s:submit> </s:form> </body> </html>