struts2.0多附件下传

struts2.0多附件上传
一、上传单个文件

上传文件是很多Web程序都具有的功能。在Struts1.x中已经提供了用于上传文件的组件。而在Struts2中提供了一个更为容易操作的上传文件组 件。所不同的是,Struts1.x的上传组件需要一个ActionForm来传递文件,而Struts2的上传组件是一个拦截器(这个拦截器不用配置, 是自动装载的)。在本文中先介绍一下如何用struts2上传单个文件,最后介绍一下用struts2上传任意多个文件。

要用Struts2实现上传单个文件的功能非常容易实现,只要使用普通的Action即可。但为了获得一些上传文件的信息,如上传文件名、上传文件类型以 及上传文件的Stream对象,就需要按着一定规则来为Action类增加一些getter和setter方法。

在Struts2中,用于获得和设置java.io.File对象(Struts2将文件上传到临时路径,并使用java.io.File打开这个临时文 件)的方法是getUpload和setUpload。获得和设置文件名的方法是getUploadFileName和 setUploadFileName,获得和设置上传文件内容类型的方法是getUploadContentType和 setUploadContentType。下面是用于上传的动作类的完整代码:


package action; 

import java.io.*; 
import com.opensymphony.xwork2.ActionSupport; 

public class UploadAction extends ActionSupport 
{ 
private File upload; 
private String fileName; 
private String uploadContentType; 

public String getUploadFileName() 
{ 
return fileName; 
} 

public void setUploadFileName(String fileName) 
{ 
this.fileName = fileName; 
} 

public File getUpload() 
{ 
return upload; 
} 

public void setUpload(File upload) 
{ 
this.upload = upload; 
} 
public void setUploadContentType(String contentType) 
{ 
this.uploadContentType=contentType; 

} 

public String getUploadContentType() 
{ 
return this.uploadContentType; 
} 
public String execute() throws Exception 
{   
  java.io.InputStream is = new java.io.FileInputStream(upload); 
  java.io.OutputStream os = new java.io.FileOutputStream("d:\\upload\\" + fileName); 
  byte buffer[] = new byte[8192]; 
  int count = 0; 
  while((count = is.read(buffer)) > 0){ 
    os.write(buffer, 0, count); 
  } 
  os.close(); 
  is.close(); 
  return SUCCESS; 
} 
} 



在execute方法中的实现代码就很简单了,只是从临时文件复制到指定的路径(在这里是d:\upload)中。上传文件的临时目录的默认值是 javax.servlet.context.tempdir的值,但可以通过struts.properties(和struts.xml在同一个目录 下)的struts.multipart.saveDir属性设置。Struts2上传文件的默认大小限制是2M(2097152字节),也可以通过 struts.properties文件中的struts.multipart.maxSize修改,如 struts.multipart.maxSize=2048 表示一次上传文件的总大小不能超过2K字节。

下面的代码是上传文件的JSP页面代码:


<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> 
<%@ taglib prefix="s" uri="/struts-tags"%> 

<html> 
<head> 
<title>上传单个文件</title> 
</head> 

<body> 
<s:form action="upload" namespace="/test" 
enctype="multipart/form-data"> 
  <s:file name="upload" label="输入要上传的文件名" /> 
  <s:submit value="上传" /> 
</s:form> 

</body> 
</html>



也可以在success.jsp页中通过<s:property>获得文件的属性(文件名和文件内容类型),代码如下:

<s:property value="uploadFileName"/> 


二、上传任意多个文件

在Struts2中,上传任意多个文件也非常容易实现。首先,要想上传任意多个文件,需要在客户端使用DOM技术生成任意多个<input type=”file” />标签。name属性值都相同。代码如下:

<html> 
<head> 
<script language="javascript"> 
var id = 0;
function addComponent() 
{ 
id = id+1;
if(id >= 5){
  alert("最多五个附件!");
  return;
}
var uploadHTML = document.createElement( "<input type='file' id='file' name='uploadFile' style='width:50%;'/>");
document.getElementById("files").appendChild(uploadHTML); 
uploadHTML = document.createElement( "<p/>"); 
document.getElementById("files").appendChild(uploadHTML); 
}
function clearFile()
{
  var file = document.getElementsByName("uploadFile");
  for(var i=0;i<file.length;i++)
  {
    file[i].outerHTML=file[i].outerHTML.replace(/(value=\").+\"/i,"$1\""); 
  }
}
</script> 
</head> 
<body> 
  <input type="button" onclick="addComponent();" value="添加文件" /> 
  <br /> 
  <form onsubmit="return true;" action="/struts2/test/upload.action" 
method="post" enctype="multipart/form-data"> 
    <table width="100%">
     <tr>
       <td style="text-align:center">
       <font style="color: red; font-size: 14px;">上传附件(文件大小请控制在20M以内)</font>
       </td>
     </tr>
     <tr>
 <td><a href="###" class="easyui-linkbutton" onclick="addComponent();" iconCls="icon-add">添加文件(最多五个附件)</a>&nbsp;<br />	  <span id="files">type='file' name='uploadFile'  style='width:50%;'/><p/>
</span>
<input type='button' value='重置' stytle='btng' onclick='clearFile();'/>
</td>
</tr>
</table> 
  </form> 
</body> 

</html> 

上面的javascript代码可以生成任意多个<input type=’file’>标签,name的值都为file(要注意的是,上面的javascript代码只适合于IE浏览器,firefox等其他 浏览器需要使用他的代码)。至于Action类,和上传单个文件的Action类基本一至,只需要将三个属性的类型改为List即可。代码如下:
package action;

import java.io.*; 
import com.opensymphony.xwork2.ActionSupport; 

public class UploadMoreAction extends ActionSupport 
{ 
private List<File> uploadFile;   
private List<String> uploadFileFileName;   
private List<String> uploadFileContentType;

public List<File> getUploadFile() {
  return uploadFile;
}

public void setUploadFile(List<File> uploadFile) {
  this.uploadFile = uploadFile;
}

public List<String> getUploadFileFileName() {
  return uploadFileFileName;
}

public void setUploadFileFileName(List<String> uploadFileFileName) {
  this.uploadFileFileName = uploadFileFileName;
}

public List<String> getUploadFileContentType() {
  return uploadFileContentType;
}

public void setUploadFileContentType(List<String> uploadFileContentType) {
  this.uploadFileContentType = uploadFileContentType;
}
public String execute() throws Exception 
{ 
if (uploads != null) 
{ 
int i = 0; 
for (; i < uploads.size(); i++) 
{ 
java.io.InputStream is = new java.io.FileInputStream(uploads.get(i)); 
java.io.OutputStream os = new java.io.FileOutputStream( 
"d:\\upload\\" + fileNames.get(i)); 
byte buffer[] = new byte[8192]; 
int count = 0; 
while ((count = is.read(buffer)) > 0) 
{ 
os.write(buffer, 0, count); 
} 
os.close(); 
is.close(); 
} 
} 
return SUCCESS; 
} 
} 


/**
	 * 保存文件
	 * @param photoPath
	 * @return
	 */
	public void saveFile(Map<String,Object> paraMap,User loginUser,List<File> uploadFile,List<String> uploadFileFileName,List<String> uploadFileContentType){
		// TODO Auto-generated method stub
		Date dateNow=new Date();
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMM");
		String dateNowStr=dateFormat.format(dateNow);
		String savePath = dateNowStr + "/"+ paraMap.get("deptCode").toString();
		if(!StringUtil.isNullOrEmpty(loginUser.getMobile())){
			savePath = savePath + "/"+ loginUser.getMobile();
		}
		String classesPath = this.getClass().getClassLoader().getResource("").getPath();
		String photoPath = com.jshx.httptransfer.utils.Constant.getPorjectPath(classesPath) + com.jshx.httptransfer.utils.Constant.filePath + savePath;
		if (uploadFile != null){   
			int i = 0;   
			for (; i < uploadFile.size(); i++){
				java.io.InputStream is;
				java.io.OutputStream os;
				
				String endSavePath = null;
				String endPath = null;
				
				try {
					is = new java.io.FileInputStream(uploadFile.get(i));
					File outdir = new File(photoPath.toString().trim());		// 新建文件
					if (!outdir.exists()){
						outdir.mkdirs();
					}
					
					String fileName = uploadFileFileName.get(i);
					String fileType = uploadFileContentType.get(i);
					Comm comm = new Comm();
					String newName = comm.getDatedFName(fileName);
					endPath = photoPath + "/"+ newName;
					endSavePath = savePath + "/"+ newName;
					
					endPath = endPath.replace(" ", "");
					endSavePath = endSavePath.replace(" ", "");
					
					File outfile = new File(endPath.toString().trim());
					if (logger.isDebugEnabled()){
						logger.debug("outdir:" + outdir.getPath());
						logger.debug("outfile:" + outfile.getPath());
					}
					if (!outfile.exists()){									//新建文本
						outfile.createNewFile();
					}
					os = new java.io.FileOutputStream(endPath); 
					byte buffer[] = new byte[8192];
					int count = 0;   
					while ((count = is.read(buffer)) > 0){   
						os.write(buffer, 0, count);
					}   
					os.close();   
					is.close();
					
					//保存到数据库
					JshxFile model = new JshxFile();
					model.setCreateTime(new Date());
					model.setCreateUserID(loginUser.getId());
					model.setDelFlag(0);
					model.setDeptId(loginUser.getDept().getId());
					model.setWorkId(paraMap.get("msgId").toString());
					model.setFilePath(endSavePath);
					model.setFileName(fileName);
					model.setFileType(fileType);
					jshxFileService.save(model);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}   
		}
	}


在execute方法中,只是对List对象进行枚举,在循环中的代码和上传单个文件时的代码基本相同。如果读者使用过struts1.x的上传组件,是 不是感觉Struts2的上传功能更容易实现呢?在Struts1.x中上传多个文件时,可是需要建立带索引的属性的。而在Struts2中,就是这么简 单就搞定了。图1是上传任意多个文件的界面。