基于struts2实现文件上传功能

   在web开发应用中,文件上传是很多情形下必备的一项功能。本文详细介绍如何通过struts2实现一个简单的文件上传功能。
 
 首先了解几个术语:
      MIME类型:设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。是描述消息内容类型的因特网标准。 MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。Tomcat的安装目录/conf/web.xml 中就定义了大量MIME类型。
      拦截器:是Struts 2的一个强有力的工具,有许多功能(feature)都是构建于它之上,如国际化、转换器,校验等。它是AOP思想的编程方式。提供一种机制使开发者能把相对独立的代码抽象出来,配置到Action前后执行。
     准备相应的jar包:commons-fileupload-1.2.1.jar;commons-io-1.4.jar;commons-logging-1.0.4.jar;freemarker-2.3.8.jar;ognl-2.6.11.jar;struts2-core-2.0.14.jar;xwork-2.0.7.jar。
     接下来编写一个Action名字叫做UploadAction,继承自ActionSupport虽然struts2的Action抛弃了request,response等Servlet API,但我们仍然可以通过ServletActionContext来得到相关Servlet对象,比如request,response,application,session等。
 

Java代码
  1. package org.common.action;   
  2.   
  3. import java.io.File;   
  4. import java.io.FileInputStream;   
  5. import java.io.FileOutputStream;   
  6.   
  7. import org.apache.struts2.ServletActionContext;   
  8.   
  9. import com.opensymphony.xwork2.Action;   
  10. import com.opensymphony.xwork2.ActionContext;   
  11. import com.opensymphony.xwork2.ActionSupport;   
  12.   
  13. @SuppressWarnings("all")   
  14. public class UploadAction extends ActionSupport {   
  15.     private File attach;   
  16.     private String attachContentType;   
  17.     private String attachFileName;   
  18.        
  19.     public String upload() throws Exception {   
  20.         File saved = new File(ServletActionContext.getServletContext().getRealPath("uploads"), attachFileName);   
  21.         FileInputStream fis = null;   
  22.         FileOutputStream fos = null;   
  23.         try {   
  24.             saved.getParentFile().mkdirs();   
  25.             fis = new FileInputStream(attach);   
  26.             fos = new FileOutputStream(saved);   
  27.             byte[] bytes = new byte[1024];   
  28.             int len = 0;   
  29.             while ((len=fis.read(bytes))!=-1) {   
  30.                 fos.write(bytes, 0, len);                  
  31.             }   
  32.                
  33.                
  34.         } catch (Exception e) {   
  35.             e.printStackTrace();   
  36.         } finally {   
  37.             if (fis!=null) {   
  38.                 fis.close();   
  39.             }   
  40.             if (fos!=null) {   
  41.                 fos.close();   
  42.             }   
  43.         }   
  44.         return Action.SUCCESS;   
  45.     }   
  46.   
  47.     public File getAttach() {   
  48.         return attach;   
  49.     }   
  50.   
  51.     public void setAttach(File attach) {   
  52.         this.attach = attach;   
  53.     }   
  54.   
  55.     public String getAttachContentType() {   
  56.         return attachContentType;   
  57.     }   
  58.   
  59.     public void setAttachContentType(String attachContentType) {   
  60.         this.attachContentType = attachContentType;   
  61.     }   
  62.   
  63.     public String getAttachFileName() {   
  64.         return attachFileName;   
  65.     }   
  66.   
  67.     public void setAttachFileName(String attachFileName) {   
  68.         this.attachFileName = attachFileName;   
  69.     }   
  70.        
  71. }  
package org.common.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("all")
public class UploadAction extends ActionSupport {
	private File attach;
	private String attachContentType;
	private String attachFileName;
	
	public String upload() throws Exception {
		File saved = new File(ServletActionContext.getServletContext().getRealPath("uploads"), attachFileName);
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			saved.getParentFile().mkdirs();
			fis = new FileInputStream(attach);
			fos = new FileOutputStream(saved);
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len=fis.read(bytes))!=-1) {
				fos.write(bytes, 0, len);				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis!=null) {
				fis.close();
			}
			if (fos!=null) {
				fos.close();
			}
		}
		return Action.SUCCESS;
	}

	public File getAttach() {
		return attach;
	}

	public void setAttach(File attach) {
		this.attach = attach;
	}

	public String getAttachContentType() {
		return attachContentType;
	}

	public void setAttachContentType(String attachContentType) {
		this.attachContentType = attachContentType;
	}

	public String getAttachFileName() {
		return attachFileName;
	}

	public void setAttachFileName(String attachFileName) {
		this.attachFileName = attachFileName;
	}
	
}

 
 
      配置struts.xml文件,注意package继承struts-default的相关配置,在使用拦截器的时候,在Action里面最后一定要引用struts2自带的拦截器缺省堆栈defaultStack,不然会出错。

Xml代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC   
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"   
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.        
  6. <struts>  
  7.     <constant name="struts.multipart.maxSize" value="50000000" />  
  8.     <constant name="struts.multipart.saveDir" value="/mytemp" />  
  9.   
  10.     <package name="main" extends="struts-default">           
  11.         <!-- 所有的全局Result -->  
  12.         <global-results>  
  13.             <result name="login">/WEB-INF/jsp/login.jsp</result>  
  14.         </global-results>  
  15.            
  16.         <action name="struts" class="org.common.action.UploadAction">  
  17.             <interceptor-ref name="fileUpload">  
  18.                 <param name="allowedTypes">image/bmp, image/x-png, image/gif, image/jpeg</param>  
  19.                 <param name="maximumSize">204800</param>  
  20.             </interceptor-ref>  
  21.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  22.             <result name="input">/index.jsp</result>  
  23.             <result name="success">/WEB-INF/jsp/welcome.jsp</result>  
  24.         </action>  
  25.     </package>       
  26. </struts>  

 
      上传文件的jsp页面(注意file的name属性一定要与Action里面的File类型属性名一致):

Html代码
  1. <body>  
  2.         <s:form enctype="multipart/form-data" action="struts!upload.action" method="post">  
  3.             <s:file name="attach" label="图片附件"></s:file>  
  4.             <s:submit value="上传"></s:submit>  
  5.             <s:reset value="重置"></s:reset>  
  6.         </s:form>  
  7.            
  8. </body>  
<body>
    	<s:form enctype="multipart/form-data" action="struts!upload.action" method="post">
    		<s:file name="attach" label="图片附件"></s:file>
    	    <s:submit value="上传"></s:submit>
    	    <s:reset value="重置"></s:reset>
    	</s:form>
    	
</body>

  
      上传成功的jsp页面:
 

Html代码
  1. <%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>  
  2. <%@ taglib uri="/struts-tags" prefix="s" %>  
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  4. <html>  
  5.   <head>      
  6.     <title>登录成功</title>       
  7.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  8.     <!--  
  9.     <link rel="stylesheet" type="text/css" href="styles.css">  
  10.     -->  
  11.   </head>     
  12.   <body>  
  13.     <h1>恭喜你,<s:property value="username" />上传成功!</h1><br>  
  14.   </body>  
  15. </html>  

      总结一下:导入文件上传相关的两个组件commons-fileupload.jar和commons-io.jar,两者缺一不可;前台form表单设置enctype="multipart/form-data",file标签的name属性要与相关Action里的File属性名一致;后台定义上传Action,该Action可以定义文件的原始名称xxx与file的那么属性一致,struts会将原文件名设置到该属性上,此外还可以设置xxxContentType和xxxFileName属性,只要设置了这些都要提供相关的getter和setter方法供struts使用;根据需要使用fileUpload拦截器,从而可以限制上传文件大小和文件类型,注意上传文件大小需要在struts.multipart.maxSize属性要大于拦截器的maximumSize属性,否则maximum参数不起作用;显示使用了拦截器后,一定要将<interceptor-ref name="defaultStack"></interceptor-ref>引入;当想实现多个文件上传时,只需在Action中指定File[]或者List<File>类型的变量,并使用多个同名的<s:file />标签即可,如:

 private File[] attach;
 private String[] attachContentType;
 private String[] attachFileName;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值