一.简介
Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来。但Struts2在原有的上传解析器基础上做了进一步封装,更进一步简化了文件上传。
Struts2默认使用的是Jakarta的Common-FileUpload框架来上传文件,因此,要在web应用中增加两个Jar文件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。它在原上传框架上做了进一步封装,简化了文件上传的代码实现,取消了不同上传框架上的编程差异。
如果要改成其它的文件上传框架,可以修改struts.multipart.parser常量的值为cos/pell,默认值是jakata。并在classpath中增加相应上传组件的类库
例如配置成cos上传
struts.multipart.parser=cos
struts.multipart.maxSize=1024 指定文件的最大字结数
二.原理
不管用common-fileUPload框架,还是用cos,都是通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。
三.需要的jar包(默认使用commons-fileupload,如果使用cos,要将jar引进来)
commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.3.1.jar
commons-fileupload-1.2.jar
四.实例
1.首先,创建上传页面
- <%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%>
- <%@taglib prefix="s" uri ="/struts-tags"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'FileUpload.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">
- <s:fielderror />
- <s:file name ="upload"/>
- <s:submit />
- </s:form >
- </body>
- </html>
<%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%>
<%@taglib prefix="s" uri ="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'FileUpload.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">
<s:fielderror />
<s:file name ="upload"/>
<s:submit />
</s:form >
</body>
</html>
2.action
- package com;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.util.Date;
- import org.apache.struts2.ServletActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- public class FileUploadAction extends ActionSupport {
- private static final long serialVersionUID = 572146812454l;
- private File upload;
- private String uploadContentType;
- private String uploadFileName;
- private String imageFileName;
- public String getUploadContentType() {
- return uploadContentType;
- }
- public void setUploadContentType(String uploadContentType) {
- this.uploadContentType = uploadContentType;
- }
- public File getUpload() {
- return upload;
- }
- public void setUpload(File upload) {
- this.upload = upload;
- }
- public String getUploadFileName() {
- return uploadFileName;
- }
- public void setUploadFileName(String uploadFileName) {
- this.uploadFileName = uploadFileName;
- }
- public void setImageFileName(String imageFileName) {
- this.imageFileName = imageFileName;
- }
- public String getImageFileName() {
- return imageFileName;
- }
- private static void copy(File src, File dst) {
- try {
- InputStream in = null;
- OutputStream out = null;
- try {
- in = new BufferedInputStream(new FileInputStream(src));
- out = new BufferedOutputStream(new FileOutputStream(dst));
- byte[] buffer = new byte[1024*10];
- while (in.read(buffer) > 0) {
- out.write(buffer);
- }
- } finally {
- if (null != in) {
- in.close();
- }
- if (null != out) {
- out.close();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- @Override
- public String execute() {
- System.out.println(uploadFileName);
- imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
- File imageFile = new File(ServletActionContext.getServletContext()
- .getRealPath("/uploadImages")
- + "/" + imageFileName);
- copy(upload, imageFile);
- return SUCCESS;
- }
- }
package com;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 572146812454l;
private File upload;
private String uploadContentType;
private String uploadFileName;
private String imageFileName;
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageFileName() {
return imageFileName;
}
private static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src));
out = new BufferedOutputStream(new FileOutputStream(dst));
byte[] buffer = new byte[1024*10];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String execute() {
System.out.println(uploadFileName);
imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/uploadImages")
+ "/" + imageFileName);
copy(upload, imageFile);
return SUCCESS;
}
}
表单的enctype ="multipart/form-data,与一般的上传一样.
<s:file name="upload">会将upload绑定到action的upload,其次他还会将上传记文件的MIME类型绑定到uploadContentType,文件名绑定到uploadFileName中,他们是通过setUploadContentType和setUploadFileName进行绑定的
3.struts.xml的配置
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <constant name="struts.multipart.saveDir" value="/tmp" />
- <package name="fileUploadDemo" extends="struts-default">
- <action name ="fileUpload" class ="com.FileUploadAction">
- <!-- 验证上传文件的类型 -->
- <interceptor-ref name ="fileUpload">
- <param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>
- </interceptor-ref>
- <interceptor-ref name ="defaultStack"/>
- <!-- 如果加入了验证上传文件的类型,必须要加input -->
- <result name ="input" >/fileUpload.jsp</result>
- <result name ="success">/showUpload.jsp </result>
- </action>
- </package>
- </struts>
4.最后是web.xml的配置
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4"
- xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <filter>
- <filter-name>struts-cleanup</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ActionContextCleanUp
- </filter-class>
- </filter>
- <filter>
- <filter-name>struts2</filter-name >
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class >
- </filter>
- <filter-mapping>
- <filter-name>struts-cleanup</filter-name >
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter-mapping>
- <filter-name>struts2</filter-name >
- <url-pattern>/*</url-pattern >
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>