struts2中单文件上传

定义jsp页面

     上传文件名称:      

失败jsp页面

<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>

文件上传失败页面

定义action

/**
* 文件上传在struts2中是由文件上传拦截器来完成该功能的
*


*/
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {

/*
* 保存上传的临时目录下的文件
* 上传文件名称:


* 默认情况下临时文件的保存路径:
* E:\\apache-tomcat-6.0.18\\work\\Catalina\\localhost\\struts2demo\\upload__1f2ff5e0_13772875cdc__8000_00000000.tmp
*/
//保存上传的临时目录下的文件.
private File uploadImage;

//保存了上传文件的类型: 格式:form表单中file组件的name属性的值+ContentType
private String uploadImageContentType;

//保存了上传文件的真实名称:格式:form表单中file组件的name属性的值+uploadImageFileName
private String uploadImageFileName;

public String saveFile(){
System.out.println("类型:"+ uploadImageContentType +" 真实名称 "+uploadImageFileName);
ServletContext sc=ServletActionContext.getServletContext();
String path=sc.getRealPath("/pic");

try {
FileUtils.copyFile(uploadImage, new File(path,uploadImageFileName));//将临时文件拷贝到指定的目录
uploadImage.delete();//删除上传的临时文件

} catch (IOException e) {
e.printStackTrace();
}

return "success";
}
.....getter setter
}

配置struts_upload.xml文件

/upload/success.jsp      




/upload/error.jsp

设置临时文件路径和大小

....

局部配置上传文件的大小和路径

2097152              

application/x-zip-compressed,application/vnd.ms-excel,text/plain

zip,xls,txt

处理上传失败时的错误信息

错误的信息来自于
struts2-core-*.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}:

中name属性的值
{1}:上传文件的名称
{2}:上传文件保存到临时目录的名称
{3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)

* 上面的是有struts2运行时动态传入

中文化失败信息

在com.yxkong.upload[任何路径都可]下
创建fileupload.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}

在struts.xml中的 标签下添加

多文件上传

public class UploadsAction extends ActionSupport {

private File[] uploadImages;
private String[] uploadImagesContentType;
private String[] uploadImagesFileName;

public String saveFiles() {

ServletContext sc = ServletActionContext.getServletContext();
String path = sc.getRealPath("/pic");

try {
if(uploadImages!=null&uploadImages.length>0){
for(int i=0;i