`
duanfei
  • 浏览: 721018 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

struts2.0多附件上传

    博客分类:
  • J2EE
阅读更多
一、上传单个文件

上传文件是很多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">
<input 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(uploadFile != null){
			Map<String, Object> paraMap = new HashMap<String, Object>();
			paraMap.put("deptCode", this.getLoginUserDepartment().getDeptCode());
			paraMap.put("workId", lawVersion.getId());
			ProjectComm pc = new ProjectComm();
			pc.saveFile(paraMap,CommCode.apkPath, this.getLoginUser(), uploadFile, uploadFileFileName, ".jpg");
		}
return SUCCESS; 
} 
} 


common.properties
UPLOAD_PATH=/virtualdir/upload/
#photo upload
PHOTO_PATH=/data/photo/


public static String getPorjectPath(String classesPath){   
        String tempdir;
        String classPath[] = classesPath.split("webapps");
        tempdir=classPath[0];
        if(!"/".equals(tempdir.substring(tempdir.length()))){
      	  tempdir += File.separator;
        }
        return tempdir;   
      }


File.separator//可以不用


FileUtil.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.jshx.ictjs.httptransfer.utils.DateTools;
import com.jsict.core.PropertiesManager;
import com.jsict.core.exception.IctException;
import com.jsict.ictmap.web.UserSession;
import com.jsict.util.IctUtil;
import com.jsict.util.StringUtil;



	private static final Logger logger = Logger.getLogger(FileUtil.class);
	
	/**
	 * 保存多文件
	 * @param paraMap	参数
	 * @param userSession	登录用户
	 * @param uploadFile	文件列表
	 * @param uploadFileFileName	文件表列表
	 * @param fileType	文件类型
	 * @throws IOException
	 * @throws IctException
	 */
	public void saveFileList(Map<String,Object> paraMap,UserSession userSession,List<File> uploadFile,List<String> uploadFileFileName,String fileType) throws IOException, IctException{
		String dateNowStr=DateTools.parseDate2Str(new Date(), "yyyyMM");
        String savePath = PropertiesManager.getProperty("common.properties", "PHOTO_PATH") + dateNowStr;
        String loginName = CommonFunc.getMapByValue(paraMap, "loginName");
        if(!StringUtil.isEmpty(loginName)){
        	savePath = savePath + "/" + loginName;
        }
        String classesPath = this.getClass().getClassLoader().getResource("").getPath();
		logger.debug("=============Constant.getPorjectPath()=" + classesPath);
		String photoPath = Constant.getPorjectPath(classesPath) + 
				PropertiesManager.getProperty("common.properties", "UPLOAD_PATH")+savePath;
		FileUtil fileUtil = new FileUtil();
		ServiceFunc sf = new ServiceFunc();
		if (uploadFile != null){
			for (int i = 0; i < uploadFile.size(); i++){
				String endSavePath = fileUtil.saveFile(photoPath, savePath,uploadFile.get(i),uploadFileFileName.get(i),fileType);
				if(!StringUtil.isEmpty(endSavePath)){
					sf.savePhoto(paraMap, userSession, endSavePath);
				}
			}   
		}
	}
	
	/**
	 * 保存文件
	 * @param photoPath	文件真实保存路径
	 * @param savePath	DB中保存的路径
	 * @param file	文件流
	 * @param filename	文件名称
	 * @param fileType	文件类型
	 * @return
	 * @throws IOException
	 */
	public String saveFile(String photoPath,String savePath,File file,String fileName,String fileType) throws IOException{
		createFolder(photoPath);
		java.io.InputStream is = null;
		java.io.OutputStream os = null;
		try {
			String newName = getDatedFName(fileName,fileType);
			String endPath = photoPath + "/"+ newName;
			String endSavePath = savePath + "/"+ newName;
			
			endPath = endPath.replace(" ", "");
			endSavePath = endSavePath.replace(" ", "");
			
			createFile(endPath.toString().trim());
			os = new java.io.FileOutputStream(endPath);
			is = new java.io.FileInputStream(file);
			byte buffer[] = new byte[8192];
			int count = 0;   
			while ((count = is.read(buffer)) > 0){   
				os.write(buffer, 0, count);
			}
			return endSavePath;
		} catch (IOException e) {
		}finally {
			if (null != is)
				is.close();
			if (null != os)
				os.close();
		}
		return null;
	}
	
	
	/**
	 * 保存文件
	 * @param request	获得二进制流
	 * @param savePath	保存相对路径
	 * @param filename	文件名称
	 * @param fileType	文件类型
	 * @return
	 * @throws IOException
	 */
	public String saveFile(HttpServletRequest request,String savePath,String fileName,String fileType) throws IOException{
		
        String classesPath = this.getClass().getClassLoader().getResource("").getPath();
		logger.debug("=============Constant.getPorjectPath()=" + classesPath);
		String photoPath = Constant.getPorjectPath(classesPath) + 
				PropertiesManager.getProperty("common.properties", "UPLOAD_PATH")+savePath;
		createFolder(photoPath);
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		try {
			String newName = getDatedFName(fileName,fileType);
			String endPath = photoPath + "/"+ newName;
			String endSavePath = savePath + "/"+ newName;
			
			endPath = endPath.replace(" ", "");
			endSavePath = endSavePath.replace(" ", "");
			
			createFile(endPath.toString().trim());
			fos = new java.io.FileOutputStream(endPath);
			bis = new BufferedInputStream(request.getInputStream());
			byte buffer[] = new byte[8192];
			int count = 0;   
			while ((count = bis.read(buffer)) > 0){   
				fos.write(buffer, 0, count);
			}
			return endSavePath;
		} catch (IOException e) {
		}finally {
			if (null != bis)
				bis.close();
			if (null != fos)
				fos.close();
		}
		return null;
	}
	
	/**
	 * 新建文件夹
	 * @param photoPath
	 */
	private void createFolder(String photoPath){
		File outdir = new File(photoPath.toString().trim());
		if (!outdir.exists()){   
			outdir.mkdirs();   
		}
	}
	
	/**
	 * 新建文本
	 * @param endPath	文件真实保存路径
	 * @throws IOException
	 */
	private void createFile(String endPath) throws IOException{
		File outfile = new File(endPath.toString().trim());
		if (logger.isDebugEnabled()){
			logger.debug("outfile:" + outfile.getPath());
		}
		if (!outfile.exists()){
			outfile.createNewFile();
		}
	}
	
	/**
	 * <照片名前加上日期>
	 * @param filename	文件名称
	 * @param fileType	文件类型
	 * @return
	 */
	public String getDatedFName(String filename,String fileType) {
		
		String fnameSplit[] = filename.split("\\.");
		
		StringBuffer result = new StringBuffer();
		int ronNum = (int)(Math.random()*1000);
		String dateSfx = IctUtil.getCurrTime() + "_" +ronNum;
		if(!StringUtil.isEmpty(fnameSplit[0])){
			result.append(fnameSplit[0]+"_");
		}
		result.append(dateSfx);
		result.append(fileType);
		return result.toString();
	}

 /** 
  * 删除某个文件夹下的所有文件夹和文件 
  * 
  * @param delpath 
  *            String 
  * @throws FileNotFoundException 
  * @throws IOException 
  * @return boolean 
  */  
 public static boolean deletefile(String delpath) throws Exception {  
  try {  
  
   File file = new File(delpath);  
   // 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true   
   if (!file.isDirectory()) {  
    file.delete();  
   } else if (file.isDirectory()) {  
    String[] filelist = file.list();  
    for (int i = 0; i < filelist.length; i++) {  
     File delfile = new File(delpath + "\\" + filelist[i]);  
     if (!delfile.isDirectory()) {  
      delfile.delete();  
      System.out  
        .println(delfile.getAbsolutePath() + "删除文件成功");  
     } else if (delfile.isDirectory()) {  
      deletefile(delpath + "\\" + filelist[i]);  
     }  
    }  
    System.out.println(file.getAbsolutePath()+"删除成功");  
    file.delete();  
   }  
  
  } catch (FileNotFoundException e) {  
   System.out.println("deletefile() Exception:" + e.getMessage());  
  }  
  return true;  
 } 
	


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


在struts.xml中可以控制上传的大小
<constant name="struts.multipart.maxSize" value="20485760" />
分享到:
评论

相关推荐

    struts2.0权威指南(完整版)part01

    找到一个网络磁盘,可以上传4G呢,链接如下: http://www.namipan.com/d/ec3e547272955230e43596936011dc901548683bb5e7d316 因为是完整版,文档有225M,不含源码,源码有380M,有需源码的童鞋可联系我邮箱lzp...

    个人知识管理系统 Struts2 + Spring + Hibernate

    采用了FCKeditor在线文本编辑器,用FCKeditor上传文件时还存在有问题,不知道是不是配置存在问题,但是图片文件利用Struts2的action上传到服务器,因为有其他附件文件要上传,并且要保存文件信息,在删除文章时要把...

    个人信息管理系统Struts2 spring hibernate dwr

    采用了FCKeditor在线文本编辑器,用FCKeditor上传文件时还存在有问题,不知道是不是配置存在问题,但是图片文件利用Struts2的action上传到服务器,因为有其他附件文件要上传,并且要保存文件信息,在删除文章时要把...

    Spring 2.0 开发参考手册

    15.4. Struts 15.4.1. ContextLoaderPlugin 15.4.2. ActionSupport 类 15.5. Tapestry 15.5.1. 注入 Spring 托管的 beans 15.6. WebWork 15.7. 更多资源 16. Portlet MVC框架 16.1. 介绍 16.1.1. 控制器 - ...

    ssh框架实现上传上载

    写的比较简陋,,基于struts1.2+spring2.0+hibernate3.1框架 基本功能: 注册,登陆,validate框架验证,文件上传,下载,简单过滤器,权限限制,下载列表查看,下载历史记录查看 未处理中文,所有jar包...

    spring chm文档

    15.4. Struts 15.4.1. ContextLoaderPlugin 15.4.2. ActionSupport 类 15.5. Tapestry 15.5.1. 注入 Spring 托管的 beans 15.6. WebWork 15.7. 更多资源 16. Portlet MVC框架 16.1. 介绍 16.1.1. 控制器 - ...

    java开源包1

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包11

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包2

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包3

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包6

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包5

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包10

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包4

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包8

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包7

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包9

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    java开源包101

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    Java资源包01

    apimms 提供了各种语言用来发送彩信(MMS)的开发包,支持附件发送。 Oracle数据库工具 WARTS WARTS是一个纯Java数据库工具,可以执行字符编码识别的数据同步。开发它是用于在UTF-8 Oracle实例中使用ASCII编码的...

    Spring-Reference_zh_CN(Spring中文参考手册)

    15.4. Struts 15.4.1. ContextLoaderPlugin 15.4.1.1. DelegatingRequestProcessor 15.4.1.2. DelegatingActionProxy 15.4.2. ActionSupport 类 15.5. Tapestry 15.5.1. 注入 Spring 托管的 beans 15.5.1.1. 将 ...

Global site tag (gtag.js) - Google Analytics