---
title: "struts2--文件上传和uploadFile拦截器"
author: "coolxing"
date: "2011-11-20T23:29:07Z"
tags: []
categories: ["编程语言"]
slug: "struts2-uploadfile"
draft: false
lastmod: "2011-11-20T21:09:12Z"
id: 1269584
url: "https://coolxing.iteye.com/blog/1269584"
---

\[coolxing按: 转载请注明作者和出处, 如有谬误, 欢迎在评论中指正.]

 

**单文件上传**

1\. 通过HTML表单上传文件时, 需要将表单的enctype属性设置为multipart/form-data, method属性设置为post. 

jsp页面代码:

```
<form action="${pageContext.request.contextPath}/upload/uploadAction_saveFile.action"
	  name="form1" method="post" enctype="multipart/form-data">
	上传文件名称: <input type="file" name="strutsUpload">
	<input type="submit" value="上传">
</form>
```

2\. 在Action类中定义一下3个成员变量, 并为其提供getter和setter方法:

```
private File strutsUpload; // 上传的文件
private String strutsUploadContentType;// 文件的类型
private String strutsUploadFileName;// 文件的名称
```

以上3个成员变量的名称不能随意更改, private File strutsUpload变量的名称必须和jsp中上传文件标签中的name属性的值一致. 而private String strutsUploadContentType变量的名称必须为"上传文件的名称+ContentType", private String strutsUploadFileName变量的名称必须为"上传文件的名称+FileName".

3\. 在Action类中定义业务方法. 完整的Action类可以如下:

```
public class UploadAction extends ActionSupport {
	private File strutsUpload; // 上传的文件
	private String strutsUploadContentType;// 文件的类型
	private String strutsUploadFileName;// 文件的名称
	// 业务方法
	public String saveFile() {
		try {
			ServletContext context = ServletActionContext.getServletContext();
			// 获得当前web应用所在目录下file文件夹的绝对路径
			String path = context.getRealPath("/file");
			File destFile = new File(path, strutsUploadFileName);
			if (!destFile.exists()) {
				destFile.createNewFile();
			}
			FileUtils.copyFile(strutsUpload, destFile);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return "success";
	}
	// 省略getter和setter方法
}
```

4\. 在struts.xml文件中配置uploadFile拦截器的属性:

```
<package name="upload" namespace="/upload" extends="struts-default">
	<action name="uploadAction_*" class="cn.xing.upload.UploadAction" method="{1}">
		<interceptor-ref name="defaultStack">
			<!--
				修改允许上传文件的大小(默认值是2M),
				将调用FileUploadInterceptor中的setMaximumSize(223434555)
			-->
			<param name="fileUpload.maximumSize">223434555</param>
			<!-- 配置允许上传文件的类型,如果有多个类型用","隔开 -->
			<param name="fileUpload.allowedTypes">application/vnd.ms-excel,text/plain</param>
			<!--配置允许上传文件的扩展名,如果有多个用","隔开  -->
			<param name="fileUpload.allowedExtensions">txt,excel,ppt</param>
		</interceptor-ref>
		<result name="success">/upload/success.jsp</result>
		<result name="input">/upload/error.jsp</result>
	</action>
</package>
```

 

**多文件上传**

多文件上传与单文件上传类似, 只有jsp表单和Action类的代码有所不同.

1\. jsp表单代码:

```
<form action="${pageContext.request.contextPath}/upload/uploadsAction_saveFiles.action"
	  name="form1" method="post" enctype="multipart/form-data">
	上传文件名称: <input type="file" name="strutsUploads"><br>
	上传文件名称: <input type="file" name="strutsUploads"><br>
	上传文件名称: <input type="file" name="strutsUploads"><br>
	<input type="submit" value="上传">
</form>
```

注意每个文件上传标签的name属性需要一致.

2\. Action类:

```
public class UploadsAction extends ActionSupport {
	private File[] strutsUploads;
	private String[] strutsUploadsContentType;
	private String[] strutsUploadsFileName;
	public String saveFiles() {
		ServletContext context = ServletActionContext.getServletContext();
		String realpath = context.getRealPath("/file");
		try {
			if (strutsUploads != null && strutsUploads.length > 0) {
				for (int i = 0; i < strutsUploads.length; i++) {
					File destFile = new File(realpath, strutsUploadsFileName[i]);
					if (!destFile.exists()) {
						destFile.createNewFile();
					}
					FileUtils.copyFile(strutsUploads[i], destFile);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}
	// 省略getter和setter方法
}
```

多文件上传时, Action中的3个成员变量的名称需要遵循与单文件上传时相同的规则. 此时3个成员变量均为数组.

3\. 在struts.xml文件中配置uploadFile拦截器的属性, 同上.

 

**错误显示**

当文件上传过程中出错时, 如果定义了错误显示页面, 将跳转到指定的页面, 并输出错误信息.

1\. 在action标签下定义如下子标签:

&lt;!-- 定义上传出错要转向的页面 --&gt;

&lt;result name="input"&gt;/upload/error.jsp&lt;/result&gt;

2\. /upload/error.jsp页面可以使用&lt;s:fielderror/&gt;标签输出错误信息.

前提是已经使用taglib指令导入了struts标签库:

&lt;%@ taglib uri="/struts-tags" prefix="s"%&gt;

3\. 默认的错误信息为英文, 在struts2-core-2.x.x.x.jar\\org\\apache\\struts2\\struts-messages.properties文件中定义:

struts.messages.error.uploading=Error uploading: {0}

struts.messages.error.file.too.large=File too large: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}

{0}:&lt;input type=“file” name=“uploadImage”&gt;中name属性的值

{1}:上传文件的名称

{2}:上传文件保存到临时目录的名称

{3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)

我们可以在Action的统计目录下创建一个fileuploadmessage.properties文件, 文件名没有要求, 但必须是properties文件, 在其中输入:

struts.messages.error.uploading=上传错误: {0}

struts.messages.error.file.too.large=文件太大: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=不支持的文件类型: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=不支持的文件扩展名: {0} "{1}" "{2}" {3}

使用jdk目录下的native2ascii工具将中文转为unicode编码.

接下来需要在struts.xml文件中加载自定义的资源文件:

&lt;constant name="struts.custom.i18n.resources" value="cn.xing.upload.fileuploadmessage"&gt;&lt;/constant&gt;