实现struts2进行文件上传

1.实现struts2进行单文件上传

 

(1)新建上传文件的jsp页面

<%@ page language=”java” import=”java.util.*” pageencoding=”utf-8”%>

<%@ page isELIgnoreed=”false”%>

<@% taglib uri=”/struts-tags” prefix=”s”%>

 

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>

<html>

  <head>

  </head>

  <body>

     <s:form action=”register” method=”post” entype=”multipart/form-data”>

        username:<s:textfield name=”username”></s:textfield>

        <br />

        <s:file name=”uploadFile”></s:file>

        <br />

        <s:submit value=”提交”></s:submit>

     </s:form>

   </body>

</html> 

(2)设计上传页面的控制层代码

     Package controller;

     import java.io.File;

     import java.io.IOException;

 

     import org.apache.commons.io.FileUtils;

     import org.apache.struts2.ServletActionContext;

     

     import org.opensymphony.xwork2.ActionSupport;

     

     Public class Register extends ActionSupport {

 

       private String username;

       private File uploadFile;

       Private String uploadFileFileName;

    

       public void validate () {

 

        }

 

         /**

          * getter() 和 setter() 方法

          **/

public String execute() throws IOException {

 

     System.out.println(“username的值是:”+username);

     String targetDirectory = ServleActionContext.getRequest().getRealPath(“/upload”);

     File target=new File(targetDirectory,uploadFileFileName);

     FileUtils.copyFile(uploadFile,target);

      Return “register”;

  }

(3) 设置上传文件的大小(struts.properties)

 

   struts.multipart.maxSize=2048000000

   struts.multipart.saveDir=/tempUploadFile

 

(4) 设置配置文件

  

   <? 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.2.dtd>

   <struts>

      <package name=”struts3.1” extends=”struts-default”>

         <action name=”register” class=”controller.Register”>

           <result name=”register”>/showregister.jsp</result>

           <result name=”input”>/register.jsp</result>

         </action>

      </package>

 <constant name=”struts.ui.theme” value=”simple”></constant>

</struts>  

 

2. 实现struts2进行多文件上传

    大体都一样,要注意在控制层代码中,定义的时候是 uploadFile[] 和 uploadFileFileName[] 数组。

     

public String execute() throws IOException {

 

     System.out.println(“username的值是:”+username);

     String targetDirectory = ServleActionContext.getRequest().getRealPath(“/upload”);

    for(int i=0;i<uploadFile.length;i++){

     File target=new File(targetDirectory,new SimpleDateFormat("yyyy_mm_dd_hh_mm_ss").format(new

       Date()).toString()+System.nanoTime()+uploadFileFileName[i]);

       FileUtils.copyFile(uploadFile[i],target);

    }   

            Return “register”;

  }

}

posted @ 2013-04-08 15:30  gexiaomin  阅读(135)  评论(0编辑  收藏  举报