`
raymond.chen
  • 浏览: 1418671 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

基于Struts2的通用文件上传实现(一)

阅读更多

    该文件上传实现可以限制上传文件的类型,限制上传文件的最大字节数,上传文件既可以存储在相对路径下,也可以存储在绝对路径下。

    一、Model类源代码

public class Attachments {
	private long id;
	private String name;  //文件名
	private String path;  //上传文件存放的子目录路径
	private Long fileSize;  //文件大小,单位为K
	private String contentType; //文件类型
	private String refName = "attachment"; //引用名称,默认为attachment,可用于区分普通附件与特殊附件。
	private String entityName; //指定与附件关联的表单的实体名称
	private String entityId; //指定与附件关联的表单的主键值
	private String creator; //创建人
	private Timestamp createDate; //创建时间
	private File attachFile; //待上传的文件对象
           ......
}

  

    二、Action类源代码

public class UploadAction extends BaseAction {
	private UploadService uploadService;
	private Attachments attach;
	
	//限制
	private String allowTypes = "";
	private long maxSize = 0; //字节
	
	//上传的文件
	private File upload;
	private String uploadFileName;
	private String uploadContentType;

	......

	//获取与表单关联的所有附件信息
	public String attachList() throws Exception{
		List attachList = uploadService.queryAttachments(attach);
		getValueStack().set("attachList", attachList);

		return SUCCESS;
	}
	
	//上传附件
	public String upload() throws Exception{
		String method = getRequest().getMethod();
		if(method.equalsIgnoreCase("post")){
			if(upload != null){
				if(upload.length() <= 0){
					throw new RuntimeException("上传的文件不能为空!");
				}
				if(maxSize > 0 && upload.length() > maxSize){
					throw new RuntimeException("上传的文件不能超过" + maxSize + "字节!");
				}
				
				allowTypes = CommonUtil.trim(allowTypes);
				if(CommonUtil.isNotEmpty(allowTypes)){
					int idx = uploadFileName.lastIndexOf(".");
					String extendName = uploadFileName.substring(idx+1); //扩展名
					List typesList = CommonUtil.toList(allowTypes, ",");
					if(!typesList.contains(extendName)){
						throw new RuntimeException("只能上传扩展名为[ " + allowTypes + " ]的文件!");
					}
				}
				
				attach.setAttachFile(upload);
				attach.setName(uploadFileName);
				attach.setFileSize(new Long(upload.length() / 1024)); //K
				attach.setContentType(uploadContentType);
				attach.setCreator(SecurityUtil.getUserId());
				attach.setCreateDate(DatetimeUtil.nowTimestamp());
				
				uploadService.addAttachment(attach);
				
			}else{
				return INPUT;
			}
		}else{
			return INPUT;
		}
		
		return SUCCESS;
	}
	
	//删除附件
	public String attachDelete() throws Exception{
		Map map = RequestUtil.getParameterMap(getRequest(), "chk_o_");
		uploadService.deleteAttachment(map);
		
		StringBuffer sb = new StringBuffer();
		sb.append("attachList.action?attach.entityName=" + CommonUtil.trim(attach.getEntityName()));
		sb.append("&attach.entityId=" + CommonUtil.trim(attach.getEntityId()));
		sb.append("&attach.refName=" + CommonUtil.trim(attach.getRefName()));
		sb.append("&attach.path=" + CommonUtil.trim(attach.getPath()));
		sb.append("&allowTypes=" + CommonUtil.trim(allowTypes));
		sb.append("&maxSize=" + maxSize);
		
		getValueStack().set("url", sb.toString());
		
		return SUCCESS;
	}
	
	//下载附件
	public String download() throws Exception{
		return SUCCESS;
	}
	
	public InputStream getTargetFile() throws Exception{
		attach = uploadService.getAttachment(attach.getId());
		uploadFileName = URLEncoder.encode(attach.getName(), "UTF-8"); //解决中文乱码问题
		
		String filePath = attach.getPath();
		if(filePath.indexOf(":") == -1){ //相对路径
			return ServletActionContext.getServletContext().getResourceAsStream(filePath);
		}else{ //绝对路径
			return new FileInputStream(filePath);
		}
	}
}

 

   三、Service类源代码

public class UploadService extends BaseService {
	/**
	 * 保存附件信息并将附件文件存储到指定目录下
	 */
	public void addAttachment(Attachments attach)throws Exception{
		if(CommonUtil.isEmpty(attach.getRefName())) attach.setRefName("attachment");
		
		//文件存储基路径
		String path = CommonUtil.trim(attach.getPath());
		if(CommonUtil.isNotEmpty(path)){
			if(path.endsWith("/") == false && path.endsWith("\\") == false){
				path += File.separator;
			}
			if(path.startsWith("/")==false && path.startsWith("\\")==false){
				if(Constants.attachBasePath.endsWith("/")==false && Constants.attachBasePath.endsWith("\\")==false){
					path = File.separator + path;
				}
			}
		}
		path = Constants.attachBasePath + path;
		attach.setPath(path);
		
		save(attach);
		
		//文件存储路径
		if(path.endsWith("/") == false && path.endsWith("\\") == false){
			path += File.separator;
		}
		path += attach.getId() + "_o_" + attach.getName();
		attach.setPath(path);
		update(attach);
		
		//目标文件
		String filePath = path;
		if(filePath.indexOf(":") == -1) filePath = ServletActionContext.getRequest().getRealPath(filePath); //不是绝对路径就转成绝对路径
		
		File dstFile = new File(filePath);
		FileUtil.createPath(dstFile.getParent()); //目标目录不存在时创建
		
		//文件保存
		try{
			FileUtil.copyFile(attach.getAttachFile(), dstFile);
		}catch(FileNotFoundException ex){
			throw new ServiceException("文件不存在:" + attach.getName());
		}
	}
	
	/**
	 * 删除选中的附件信息及其对应的文件
	 */
	public void deleteAttachment(Map map) throws ServiceException{
		List pathList = new ArrayList();
		
		for(Iterator it=map.keySet().iterator();it.hasNext();){
			String key = (String)it.next();
			String value = (String)map.get(key);
			
			Attachments attach = (Attachments)load(Attachments.class, new Long(value));
			if(attach != null){
				pathList.add(attach.getPath());
				delete(attach);
			}
		}
		
		for(int i=0;i<pathList.size();i++){
			String filePath = (String)pathList.get(i);
			if(filePath.indexOf(":") == -1){
				filePath = ServletActionContext.getRequest().getRealPath(filePath);
			}
			File file = new File(filePath);
			FileUtil.deleteFile(file);
		}
	}
	
	/**
	 * 查找附件
	 */
	public List queryAttachments(Attachments attach)throws Exception{
		DetachedCriteria dc = DetachedCriteria.forClass(Attachments.class);
		CriteriaUtil.eq(dc, "entityName", attach.getEntityName());
		CriteriaUtil.eq(dc, "entityId", attach.getEntityId());
		CriteriaUtil.eq(dc, "refName", attach.getRefName());

		dc.addOrder(Order.asc("createDate"));
		
		return findByCriteria(dc);
	}
	
	public Attachments getAttachment(long id)throws Exception{
		return (Attachments)load(Attachments.class, new Long(id));
	}
}

 

分享到:
评论
4 楼 韩悠悠 2011-01-10  
eric851018 写道

我就喜欢你这种写法

多看看源代码,尤其是spring,这种写法很一般。
3 楼 eric851018 2010-10-26  

我就喜欢你这种写法
2 楼 osacar 2010-09-12  
不错,比其他那些好多了。
1 楼 qiaoakai 2009-05-26  
太好了,如果 要把源码作为附件 能下载  那就更好了!!谢谢了 呵呵

相关推荐

    struts2必须包

    struts2必须包,commons-fileupload-1.3.1.jar 实现文件上传包,commons-io-2.2.jar 用来处理IO的一些工具类包,commons-lang3-3.1.jar 提供一些基础的、通用的操作和处理,如自动生成toString()的结果、自动实现...

    Struts2 in action中文版

    3.5 案例研究:文件上传 56 3.5.1 通过struts-default包获得内建的支持 56 3.5.2 fileUpload拦截器做什么 57 3.5.3 Struts 2公文包示例代码研究 58 3.6 小结 60 第4章 使用拦截器追加工作流 61 4.1 为什么要拦截...

    深入浅出Struts2(附源码)

    作者处处从实战出发,在丰富的示例中直观地探讨了许多实用的技术,如数据类型转换、文件上传和下载、提高Struts 2应用的安全性、调试与性能分析、FreeMarker、Velocity、Ajax,等等。跟随作者一道深入Struts 2,聆听...

    深入浅出Struts 2 .pdf(原书扫描版) part 1

    如数据类型转换、文件上传和下载、Struts2应用的安全性、调试与性能分析、FreeMarker、Velocily、Ajax,等等。跟随作者一道深入Struts2。聆听大量来之不易的经验之谈。你对Struts2开发框架的理解和应用水平都将更上...

    java+mysql实现的代码分享网(所有源码已开源,效果可看网址:www.admintwo.com)

    同时也实现了文件上传(基于struts2的文件上传功能)。 4、代码下载,下载功能会判断用户是否下载过该代码,若下载过则不扣积分。下载功能也是基于struts2的下载模块实现的。 5、代码评论,该功能是我仿照qq空间评论...

    JAVA上百实例源码以及开源项目

    5个目标文件,演示Address EJB的实现,创建一个EJB测试客户端,得到名字上下文,查询jndi名,通过强制转型得到Home接口,getInitialContext()函数返回一个经过初始化的上下文,用client的getHome()函数调用Home接口...

    基于J2EE框架的个人博客系统项目毕业设计论文(源码和论文)

    1、 Struts是一个为开发基于模型(Model)-视图(View)-控制器(Controller)(MVC)模式的应用架构的开源框架,是利用Servlet,JSP和custom tag library构建Web应用的一项非常有用的技术。由于Struts能充分满足应用开发...

    java开源包2

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包3

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包4

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    JAVA上百实例源码以及开源项目源代码

    5个目标文件,演示Address EJB的实现,创建一个EJB测试客户端,得到名字上下文,查询jndi名,通过强制转型得到Home接口,getInitialContext()函数返回一个经过初始化的上下文,用client的getHome()函数调用Home接口...

    java开源包1

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包11

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包6

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包5

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包10

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

    java开源包8

    Java文件上传组件 COS FAT文件系统读写类库 fat32-lib fat32-lib 是一个用来读写 FAT 16/32 格式文件系统的纯 Java 类库(纯的)。 Eclipse的HTML格式化插件 Eclipse Tidy Eclipse HTML Tidy 是一款 Eclipse 的...

Global site tag (gtag.js) - Google Analytics