`
raymond.chen
  • 浏览: 1426204 次
  • 性别: 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架构设计与实现原理

    Struts2是Java Web开发中一个非常重要的框架,它基于Model-View-Controller(MVC)设计模式,为开发者提供了一种结构化的解决方案,简化了Web应用的开发过程。本书《Struts2技术内幕——深入解析Struts2架构设计与...

    基于Struts2的班级网站

    总的来说,这个基于Struts2的班级网站项目涵盖了Struts2框架的多个关键方面,对于初学者来说,这是一个很好的实践平台,可以深入理解MVC架构、Action、拦截器、结果类型、文件上传以及用户状态管理等核心概念。...

    ssh2(struts2+spring2.5+hibernate3.3+ajax)带进度条文件上传(封装成标签)

    标题 "ssh2(struts2+spring2.5+hibernate3.3+ajax)带进度条文件上传(封装成标签)" 涉及到的是一个基于Java Web的项目,利用了Struts2、Spring2.5、Hibernate3.3和Ajax技术,实现了文件上传并带有进度条显示的功能...

    struts2常用的13个jar包

    4. **javassist-3.11.0.GA.jar**:Javassist是一个Java字节码操作和分析框架,Struts2使用它来动态地修改或生成类,例如在运行时实现方法拦截。 5. **log4j-1.2.17.jar**:这是一个流行的日志记录框架,Struts2使用...

    java struts2 上传包含jad等文件类型

    在Struts2中,文件上传是通过`CommonsFileUpload`库来实现的,这是一个Apache Commons项目,用于处理HTTP请求中的多部分数据,也就是通常的文件上传。在提供的文件列表中,`commons-fileupload-1.2.1.jar`就是这个库...

    struts文件上传下载

    4. **Interceptor拦截器**:Struts2的拦截器可以用来实现通用的文件上传和下载逻辑,例如限制上传大小,记录日志等。 5. **安全性**:文件上传可能导致安全问题,如代码注入、跨站脚本攻击(XSS)。因此,确保对...

    struts拦截器+文件上传

    通过理解以上知识点,并结合提供的"拦截器+文件上传判断类型"这个文件,你可以创建一个自定义的拦截器来实现对文件上传的全面控制,包括类型判断、大小检查等,确保文件上传功能的安全和稳定。在实际开发中,还需...

    struts2用到的各种架包

    Struts2是一个强大的Java EE(Enterprise Edition)框架,主要用于构建基于MVC(Model-View-Controller)模式的Web应用程序。这个框架提供了丰富的功能,包括动作调度、数据绑定、异常处理、国际化支持等,大大简化...

    struts2必须包

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

    Struts2 apps

    3. **Interceptor(拦截器)**:拦截器是Struts2的一大特色,它们在Action调用前后执行,可以实现如日志记录、权限检查、事务管理等通用功能。 4. **Result类型**:Result定义了Action执行后如何展示结果,如转发到...

    struts2基本(最小)jar包

    这些JAR文件是构建基于Struts2的应用的基础,缺少任何一个都可能导致应用无法正常运行。以下是对这些核心组件的详细介绍: 1. **.struts2-core.jar**:这是Struts2框架的核心库,包含Action、Result、Interceptor等...

    Struts2框架

    拦截器是Struts2的一大特色,可以实现如日志、权限检查、事务管理等通用功能,并且可以按需组合使用。结果类型则是决定Action执行完成后如何跳转到视图页面。 Struts2的Action支持多种结果类型,包括JSP、...

    配置struts2需要的资源包

    在开发基于Struts2的应用时,正确配置和选用所需的资源包至关重要,这能确保项目的稳定性和高效性。在这个“配置struts2需要的资源包”的主题中,我们将详细探讨Struts2的核心组件、依赖库以及如何精简不必要的包。 ...

    Struts2项目必需jar包

    最后,为了保证兼容性和安全性,可能还需要包括`commons-fileupload.jar`和`commons-io.jar`,它们负责处理HTTP上传文件,以及提供通用的I/O操作。 在构建Struts2项目时,确保所有这些必需的jar包都已正确引入并...

    struts2需要的jar包

    Struts2是一个非常著名的Java Web开发框架,由Apache软件基金会维护。它基于MVC(Model-View-Controller)设计模式,旨在简化Web应用程序的开发,提高可维护性和可扩展性。Struts2提供了丰富的功能,如拦截器、插件...

    jsp+struts+mysql支持支持添加分类及商品文件上传

    该大作业是一个基于JavaWeb技术实现的在线购物平台,主要运用了JSP(JavaServer Pages)、Struts框架和MySQL数据库。下面将详细讲解这些技术及其在项目中的应用。 首先,JSP是Java的一种动态网页技术,它允许开发...

    struts2-lib

    - `commons-fileupload`: 处理HTTP文件上传的库,Struts2使用它来支持用户上传文件。 - `commons-lang3`: Apache Commons提供的Java实用工具类库,增强Java的基本功能。 - `javassist`: 动态代码生成库,Struts2...

    struts2必要的包免费下载

    2. **依赖的Apache Commons库**:Struts2依赖于Apache Commons家族的多个库,如Commons FileUpload用于文件上传,Commons Logging用于日志记录,Commons Lang用于提供通用的Java语言工具等。 3. **插件库**:Struts...

    struts2学习笔记一

    Struts2是Java开发中的一个强大的MVC(Model-View-Controller)框架,它极大地简化了基于Java的企业级应用程序的构建过程。作为Apache软件基金会的开源项目,Struts2是在Struts1的基础上,结合WebWork的技术发展起来...

    Struts2 jar包

    这个压缩包提供了一个完整的Struts2开发环境,包括核心库和其他必要的依赖包,以便开发者可以顺利地进行基于Struts2的项目开发。 1. **Struts2核心框架**: Struts2的核心框架提供了MVC(模型-视图-控制器)架构,...

Global site tag (gtag.js) - Google Analytics