概述
在上传文件时,可以对上传的文件进行大小、格式进行控制。在Struts2中提供了文件上传拦截器(fileUpload),该拦截器能够实现对上传文件的过滤功能。
- fileUpload拦截器常用属性有:
- maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be seton the action. Note, this is not related to the various properties found in struts.properties.Default to approximately 2MB.
- allowedTypes (optional) - a comma separated list of content types (ie: text/html) that the interceptor will allowa file reference to be set on the action. If none is specified allow all types to be uploaded.
- allowedExtensions (optional) - a comma separated list of file extensions (ie: .html) that the interceptor will allowa file reference to be set on the action. If none is specified allow all extensions to be uploaded.
- 文件上传过滤
1 基于表单的文件上传
HTML基于表单的文件上传
<form action="${pageContext.request.contextPath}/up/upload" enctype="multipart/form-data" method="post">
<input type="file" name="UpImg">
<input type="submit" value="上传">
</form>
不要忘了enctype="multipart/form-data"
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
默认地,表单数据会编码为 “application/x-www-form-urlencoded”。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 “+” 加号,特殊符号转换为 ASCII HEX 值)。
enctype的用法 出处:http://www.cnblogs.com/lightsong/
首先,只有使用POST方法的时候enctype才生效,GET方法默认使用 application/x-www-form-urlencoded 编码方法。
构造一个含有file控件的form, 还包括一个input框, 变化enctype为以下值, 查看请求报文都是按照 application/x-www-form-urlencoded 编码的:
1、 不书写 enctype 属性
<form id="fileupload" name="fileupload" method="post" action="/index.php">
2、 书写enctype但是值为空:
<form id="fileupload" name="fileupload" method="post" action="/index.php" enctype="">
3、 书写enctype值为未定义值:
<form id="fileupload" name="fileupload" method="post" action="/index.php" enctype="sss">
4、 书写enctype为
<form id="fileupload" name="fileupload" method="post" action="/index.php" enctype="application/x-www-form-urlencoded">
修改enctype为 multipart/form-data
<form id="fileupload" name="fileupload" method="post" action="/index.php" enctype="multipart/form-data">
对于文件上传来说, 要读取文件的内容, 不能使用 ServletRequest 接口的 getParameter()
方法, 而需要调用 ServletRequest 接口的 getlnputStreamO方法来得到输入流, 然后从输入
流中读取传送的内容, 再根据文件上传的格式进行分析, 取出上传文件的内容和表单中其
他字段的内容。
2 Struts 对文件上传的支持
- commons-fileupload - 1.2.1.jar
- commons-io-1.4.jar
Struts 2 提供了一个文件上传拦截器: org.apache.struls2.interceplor.FileUploadInterceptor
它负责调用底层的文件上传组件解析文件内容, 并为 Action 准备与上传文件相关的属性
值。 处理文件上传请求的 Action 必须提供特殊样式命名的属性, 例如, 假设表单中文件选
择框〈( input type=“file” name=“image”>) 的名字是 image, 那么 action 应该提供下列三个
属性
3 实现文件上传步骤
- upload.jsp
<s:form action="upload" method="POST" enctype="multipart/form-data">
<s:file name="file" label="选择上传的文件"></s:file>
<s:textfield label="文件描述" name="description"></s:textfield>
<s:submit value="上传"></s:submit>
</s:form>
- action编写
public class UploadAction extends ActionSupport {
// 代表上传文件的 file 对象
private File file;
// 上传文件名
private String fileFileName;
// 上传文件的 MIME 类型
private String fileContentType;
//上传文件的描述信息
private String description;
//保存上传文件的目录, 相对于 Web 应用程序的根路径, 在 struts.xml 文件中配置
private String uploadDir;
省略getset方法
@Override
public String execute() throws Exception {
String newFileName = null;
// 得到当前时间自 1970 年 1 月1 日 0 时 0 分 0 秒开始流逝的毫秒数, 将这个毫秒数作为上传文件新的文件名
long now = new Date().getTime();
//得到保存上传文件的目录的真实路径
String path = ServletActionContext.getServletContext().getRealPath(uploadDir);
System.out.println(path);
File dir = new File(path);
//如果不存在则创建
if (!dir.exists())
dir.mkdir();
int index = fileFileName.lastIndexOf(".");
// 判断上传文件名是否有扩展名, 以时间戳作为新的文件名
if (index != -1) {
newFileName = now + fileFileName.substring(index);
} else {
newFileName = Long.toString(now);
}
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
// 读取保存在tt时目录下的上传文件, 写入到新的文件中
try {
FileInputStream fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(new File(dir, newFileName));
bos = new BufferedOutputStream(fos);
byte[] buf = new byte[4096];
int len = -1;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (null != bis)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != bos)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return SUCCESS;
}
- xml配置
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.i18n.encoding" value="GBK"></constant>
<constant name="struts.multipart.saveDir" value="d:\\temp"></constant>
<package name="test" extends="struts-default" namespace="/" strict-method-invocation="true">
<action name="upload" class="com.rain.action.UploadAction">
<result name="success">index.jsp</result>
<param name="uploadDir">/WEB-INF/UploadFiles</param>
</action>
</package>
总结
你在Action 中对上传文件进行处理的时候, 上传文件已经在版务器上了。FileUploadlnterceptor拦截器在为 Action 准备上传文件之前, 就已经调用底层的上传组件接收了客户端上传的文件, 并将它保存到一个临时目录中, 然后再为 Action 提供上传文件的各种信息。
<constant name="struts.multipart.saveDir" value="d:\\temp"></constant>
可以设置临时保存的文件。也就是文件先保存在临时文件夹中,等action处理好上传的文件之后在删除。FileUploadlnterceptor 拦截器会自动帮我们把临时文件删除。
当没有 struts.multipart.saveDir 属性的设置的时候 , 缺省使用javax.servlet.context.tempdir 表示的路径来存放上传的临时文件。
要注意Struts2默认文件上传最大为2M即便你设置了
<param name="maximumSize">5242880</param>
当上传的文件大于2M时候也会出错的,这时要设置,另外一个常量
<constant name="struts.multipart.maxSize" value="1000000000"/>
对文件上传进行更多的控制,FileUploadlmerceptor 拦截器可以配K 两个参数.用于对文件上传进行控制。 这两个参数如下所示:
- maximumSize: 通知拦截器 Action 可接受的文件的最大长度 ( 以字节为单位), 默认认值为 2MB.
- allowedTypes: 以逗号分隔的内容类型的列表( 例如: text/html ), 符合列表中的类型的文件, 可以被传给 Action。 如果没有指定这个参数, 那么就是允许任何上传类型。
<!-- 指定(限制)上传文件的类型,定义局部拦截器,修改默认拦截器的属性
"fileUpload.maximumSize" :限制上传最大的文件大小。
"fileUpload.allowedTypes":允许上传文件的类型。
"fileUpload.allowedExtensions":允许上传文件的可扩展文件类型。 -->
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">500000000</param>
<param name="fileUpload.allowedTypes">text/plain,application/vnd.ms-powerpoint</param>
<param name="fileUpload.allowedExtensions">.txt,.ppt,image/gif,image/jpeg</param>
</interceptor-ref>
详细查看 http://tool.oschina.net/commons
Content-Type的类型如下:
- 常见的媒体格式类型如下:
text/html : HTML格式
text/plain :纯文本格式
text/xml : XML格式
image/gif :gif图片格式
image/jpeg :jpg图片格式
image/png:png图片格式- 以application开头的媒体格式类型:
application/xhtml+xml :XHTML格式
application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式
application/json : JSON数据格式
application/pdf :pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded :<form encType="">
中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)- 另外一种常见的媒体格式是上传文件之时使用的:
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
如果你的action实现了ValidationAware接口
(如果action继承了ActionSupport,那么就相当于实现了ValidationAware),
这个拦截器就可以添加几种字段错误.这些错误信息是基于存储在struts-messages.properties文件中的一些i18n值,这个文件是所有i18n请求的默认文件.
你可以在自己消息文件的复写以下key的消息文字
struts.messages.error.uploading-文件不能上传的通用错误信息 struts.messages.error.file.too.large-上传文件长度过大的错误信息 struts.messages.error.content.type.not.allowed-当上传文件不符合指定的contentType
如果仅仅是保存文件。那这个比较简单。
//得到上传文件在服务器的路径加文件名
String target=ServletActionContext.getServletContext().getRealPath("/upload/"+fileFileName);
//获得上传的文件
File targetFile=new File(target);
//通过struts2提供的FileUtils类拷贝
try {
FileUtils.copyFile(file, targetFile);
} catch (IOException e) {
e.printStackTrace();
}
限制上传文件的最大长度
fileUpload 拦截器的 maximumSize 参数只是设定 Action 能接受的文件的最大长度
( 在Action 处理之前, 文件已经上传到服务器上了), 而不是对上传文件的最大长度进行限制。
如果要对上传文件的最大长度进行限制, 可以通过设struts.muitipart.maxSize 属性来实现, 该属性将直接影响 Struts 2 框架底层使用的 commons-fileupload 组件对文件的接收处理。
如 果 上 传 的 文 件 长 度 大 于 struts.muitipart.maxSize 属 性 的 值 , 那 么 底 层 的
commons-fileupload 组 件 将 抛 出 org.apache.commons.fileupload.FileUploadBase$SizeLimit
ExceededException 异常, 上传文件拦截器捕获到该异常后, 将直接把该异常的消息设置为
Action 级别的错误消息。 如果你在页面中使用<actionerror>
标签, 将看到如下的错误:
the request was rejected because its size (6249303) exceeds the configured
(2097152)
编辑 struls.xml 文件, 添加 struts.muitipart.maxSize W性的设置, 如下所示:
<constant name=-struts.multipart.maxSize- value=-102400-/>
编辑 upload.jsp, 在<form>
标签的上方添加<s:actionerror/>
标签的调用。