struts2上传文件

通过2种方式模拟单个文件上传,效果如下所示

开发步骤如下:

1、新建一个web工程,导入struts2上传文件所需jar,如下图

目录结构

            

2、新建Action 


  1. package com.ljq.action;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.apache.commons.io.FileUtils;  
  6. import org.apache.struts2.ServletActionContext;  
  7.   
  8. import com.opensymphony.xwork2.ActionContext;  
  9. import com.opensymphony.xwork2.ActionSupport;  
  10.   
  11. @SuppressWarnings("serial")  
  12. public class UploadAction extends ActionSupport{  
  13.       
  14.     private File image; //上传的文件  
  15.     private String imageFileName; //文件名称  
  16.     private String imageContentType; //文件类型  
  17.   
  18.     public String execute() throws Exception {  
  19.        //设置文件上传的路径默认在当前项目的根目录下
  20.         String realpath = ServletActionContext.getServletContext().getRealPath("/images");  
  21.         //D:\apache-tomcat-6.0.18\webapps\struts2_upload\images  
  22.         System.out.println("realpath: "+realpath);  
  23.         if (image != null) {  
  24.             File savefile = new File(new File(realpath), imageFileName);  
  25.             if (!savefile.getParentFile().exists())  
  26.                 savefile.getParentFile().mkdirs();  
  27.             FileUtils.copyFile(image, savefile);  
  28.             ActionContext.getContext().put("message""文件上传成功");  
  29.         }  
  30.         return "success";  
  31.     }  
  32.   
  33.   get.set方法省略
  34.   
  35.       
  36. }  
 

第二种

  1. package com.ljq.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8. import org.apache.struts2.ServletActionContext;  
  9.   
  10. import com.opensymphony.xwork2.ActionSupport;  
  11.   
  12. @SuppressWarnings("serial")  
  13. public class UploadAction2 extends ActionSupport {  
  14.   
  15.     // 封装上传文件域的属性   
  16.     private File image;  
  17.     // 封装上传文件类型的属性   
  18.     private String imageContentType;  
  19.     // 封装上传文件名的属性   
  20.     private String imageFileName;  
  21.     // 接受依赖注入的属性   
  22.     private String savePath;  
  23.   
  24.     @Override  
  25.     public String execute() {  
  26.         FileOutputStream fos = null;  
  27.         FileInputStream fis = null;  
  28.         try {  
  29.             // 建立文件输出流   
  30.             System.out.println(getSavePath());  
  31.             fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName());  
  32.             // 建立文件上传流   
  33.             fis = new FileInputStream(getImage());  
  34.             byte[] buffer = new byte[1024];  
  35.             int len = 0;  
  36.             while ((len = fis.read(buffer)) > 0) {  
  37.                 fos.write(buffer, 0, len);  
  38.             }  
  39.         } catch (Exception e) {  
  40.             System.out.println("文件上传失败");  
  41.             e.printStackTrace();  
  42.         } finally {  
  43.             close(fos, fis);  
  44.         }  
  45.         return SUCCESS;  
  46.     }  
  47.   
  48.     /** 
  49.      * 返回上传文件的保存位置 
  50.      *  
  51.      * @return 
  52.      */  
  53.     public String getSavePath() throws Exception{  
  54.         return ServletActionContext.getServletContext().getRealPath(savePath);   
  55.     }  
  56.   
  57.     public void setSavePath(String savePath) {  
  58.         this.savePath = savePath;  
  59.     }  
  60.   
  61.     public File getImage() {  
  62.         return image;  
  63.     }  
  64.   
  65.     public void setImage(File image) {  
  66.         this.image = image;  
  67.     }  
  68.   
  69.     public String getImageContentType() {  
  70.         return imageContentType;  
  71.     }  
  72.   
  73.     public void setImageContentType(String imageContentType) {  
  74.         this.imageContentType = imageContentType;  
  75.     }  
  76.   
  77.     public String getImageFileName() {  
  78.         return imageFileName;  
  79.     }  
  80.   
  81.     public void setImageFileName(String imageFileName) {  
  82.         this.imageFileName = imageFileName;  
  83.     }  
  84.   
  85.     private void close(FileOutputStream fos, FileInputStream fis) {  
  86.         if (fis != null) {  
  87.             try {  
  88.                 fis.close();  
  89.             } catch (IOException e) {  
  90.                 System.out.println("FileInputStream关闭失败");  
  91.                 e.printStackTrace();  
  92.             }  
  93.         }  
  94.         if (fos != null) {  
  95.             try {  
  96.                 fos.close();  
  97.             } catch (IOException e) {  
  98.                 System.out.println("FileOutputStream关闭失败");  
  99.                 e.printStackTrace();  
  100.             }  
  101.         }  
  102.     }  
  103.   
  104. }  
 

struts.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.     <!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。  
  8.         如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->  
  9.     <constant name="struts.action.extension" value="do,action" />  
  10.     <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->  
  11.     <constant name="struts.serve.static.browserCache" value="false" />  
  12.     <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->  
  13.     <constant name="struts.configuration.xml.reload" value="true" />  
  14.     <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->  
  15.     <constant name="struts.devMode" value="true" />  
  16.     <!-- 默认的视图主题 -->  
  17.     <constant name="struts.ui.theme" value="simple" />  
  18.     <!--<constant name="struts.objectFactory" value="spring" />-->  
  19.     <!--解决乱码    -->  
  20.     <constant name="struts.i18n.encoding" value="UTF-8" />  
  21.     相当于request.setCharacterEncoding("utf-8");
  22.     <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->  
  23.     <constant name="struts.multipart.maxSize" value="10701096"/>  
  24.     <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->  
  25.     <constant name="struts.multipart.saveDir " value="d:/tmp" />  
  26.       strtus2框架默认加载的文件
  27.      <constant name="struts.configuration.files" value="struts-default.xml,struts-plugin.xml,struts.xml"/>
  28.      
  29.      <constant name="struts.i18n.reload"  value="true"/>   该属性设置是否每次HTTP请求到达时,系统都重新加载资源文件。该属性默认值是false。在开发阶段将该属性设置为true会更有利于开发,但在产品发布阶段应将该属性设置为false,
    提示 开发阶段将该属性设置了true,将可以在每次请求时都重新加载国际化资源文件,从而可以让开发者看到实时开发效果;产品发布阶段应该将该属性设置为false,是为了提供响应性能,每次请求都需要重新加载资源文件会大大降低应用的性能
  1.            
  2.     <package name="upload" namespace="/upload" extends="struts-default">  
  3.         <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">  
  4.             <result name="success">/WEB-INF/page/message.jsp</result>  
  5.         </action>  
  6.     </package>  
  7.       
  8.     <package name="upload2" extends="struts-default">  
  9.         <action name="upload2" class="com.ljq.action.UploadAction2" method="execute">  
  10.             <!-- 动态设置savePath的属性值 -->  
  11.             <param name="savePath">/images</param>  
  12.             <result name="success">/WEB-INF/page/message.jsp</result>  
  13.             <result name="input">/upload/upload.jsp</result>  
  14.             <interceptor-ref name="fileUpload">  
  15.                 <!-- 文件过滤 -->  
  16.                 <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>  
  17.                 <!-- 文件大小, 以字节为单位 -->  
  18.                 <param name="maximumSize">1025956</param>  
  19.             </interceptor-ref>  
  20.             <!-- 默认拦截器必须放在fileUpload之后,否则无效 -->  
  21.             <interceptor-ref name="defaultStack" />  
  22.         </action>  
  23.     </package>  
  24. </struts>  
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
        如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
    <constant name="struts.action.extension" value="do" />
    <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默认的视图主题 -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--解决乱码    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
    
         
    <package name="upload" namespace="/upload" extends="struts-default">
        <action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
            <result name="success">/WEB-INF/page/message.jsp</result>
        </action>
    </package>
    
    <package name="upload2" extends="struts-default">
        <action name="upload2" class="com.ljq.action.UploadAction2" method="execute">
            <!-- 动态设置savePath的属性值 -->
            <param name="savePath">/images</param>
            <result name="success">/WEB-INF/page/message.jsp</result>
            <result name="input">/upload/upload.jsp</result>
            <interceptor-ref name="fileUpload">
                <!-- 文件过滤 -->
                <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param>
                <!-- 文件大小, 以字节为单位 -->
                <param name="maximumSize">1025956</param>
            </interceptor-ref>
            <!-- 默认拦截器必须放在fileUpload之后,否则无效 -->
            <interceptor-ref name="defaultStack" />
        </action>
    </package>
</struts>

上传表单页面

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@taglib uri="/struts-tags" prefix="s" %>  
  3.   
  4. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  5. <html>  
  6.     <head>  
  7.         <title>文件上传</title>  
  8.   
  9.         <meta http-equiv="pragma" content="no-cache">  
  10.         <meta http-equiv="cache-control" content="no-cache">  
  11.         <meta http-equiv="expires" content="0">  
  12.     </head>  
  13.   
  14.     <body>  
  15.         <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->  
  16.         <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->  
  17.         <form action="${pageContext.request.contextPath}/upload2/upload2.do"   
  18.               enctype="multipart/form-data" method="post">  
  19.             文件:<input type="file" name="image">  
  20.                 <input type="submit" value="上传" />  
  21.         </form>  
  22.         <br/>  
  23.         <s:fielderror />  
  24.     </body>  
  25. </html>  
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>文件上传</title>

        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
    </head>

    <body>
        <!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
        <!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
        <form action="${pageContext.request.contextPath}/upload2/upload2.do" 
              enctype="multipart/form-data" method="post">
            文件:<input type="file" name="image">
                <input type="submit" value="上传" />
        </form>
        <br/>
        <s:fielderror />
    </body>
</html>

显示结果页面

  1. <%@ page language="java" import="java.util.*" 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.       
  7.     <title>上传成功</title>  
  8.       
  9.     <meta http-equiv="pragma" content="no-cache">  
  10.     <meta http-equiv="cache-control" content="no-cache">  
  11.     <meta http-equiv="expires" content="0">      
  12.   </head>  
  13.     
  14.   <body>  
  15.     上传成功!  
  16.     <br/><br/>  
  17.     <!-- ${pageContext.request.contextPath} tomcat部署路径,  
  18.           如:D:\apache-tomcat-6.0.18\webapps\struts2_upload\ -->  
  19.     <img src="${pageContext.request.contextPath}/<s:property value="'images/'+imageFileName"/>">  
  20.     <s:debug></s:debug>  
  21.   </body>  
  22. </html>  
  23. Struts2框架通过validateable实现数据验证功能
  24. ActionSupport类实现了validateable接口(该接口一个方法validate()方法),
  25. public ValidateAction extends ActionSupport implments Validateable{
  26.     private String msg;
  27.     get.set方法……
  28.     public String validate(){
  29.           System.out.println("success");
  30.           return "success";
  31.     }
  32.    public void validate(){
  33.       if(msg.equalsEgnormal("hello")){
  34.             this.addActionMessage("提交成功");
  35.       }else{
  36.             System.out.pritnln(“input”);
  37.             this.addFieldError("msg.hello","必须输入hello");
  38.             this.addActioinError("表单提交失败");
  39.        }
  40.    }
  41. }
  42. validate.jsp页面:
  43.  <s:actionerror/>动作错误信息,有则显示无则不显示
     <s:fielderror/>字段错误信息,有则显示无则不显示
     <s:actionmessage/>动作信息,有则显示无则不显示
     <s:form action="file/ValidateAction_execute.action" theme="simple">
      <s:textfield name="msg"></s:textfield>
      <!-- 错误信息 -->
      <s:fielderror cssStyle="color:red"></s:fielderror>
      <s:actionerror key="msg.hello" cssStyle="color:blue"/>
      <br/>
      <s:submit/>
     </s:form>
  44. struts.xml文件
  45. <package name="defaultPackage" extends="struts-default" namespace="/file">
     <action name="*_*" class="useraction.{1}" method="{2}">
     <!-- 配置fileUpload的拦截器 -->
    <interceptor-ref name="fileUpload">
     <!-- 配置允许上传的文件类型 -->
    <param name="allowedTypes"></param>
     <!-- 配置允许上传的文件大小 单位字节-->
    <param name="maximumSize">1000</param>
    </interceptor-ref>
    <interceptor-ref name="defaultStack"/>
    <result name="success">/success.jsp</result>
    <result name="input">/AddProducts.jsp</result>
    <result>/validate.jsp</result>
    <result name="input">/validate.jsp</result>//input返回至是struts2默认的在action 里面配置
  46. 请求在进入Action里面首先调用validate()方法,正确才会继续调用execute()方法,否则不调用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值