首页 > 代码库 > strut2 多个文件上传

strut2 多个文件上传

  1. 在单个文件上传的基础上,修改action中的属性类型,多个文件上传其实就是通过数组或者list来接收文件。客户端上传表单代码如下所示:
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>My JSP ‘employeeAdd.jsp‘ starting page</title>        <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">  </head>    <body>    <form action="${pageContext.request.contextPath}/control/employee/list_execute.action" enctype="multipart/form-data" method="post">        文件1:<input type="file" name="image"><br/>        文件2:<input type="file" name="image"><br/>        文件3:<input type="file" name="image"><br/>        <input type="submit" value="上传"/>    </form>  </body></html>

    2.在action中的代码如下所示:

    package cn.itcast.action;import java.io.File;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class HelloWorldAction {    private File[] image;    private String[] imageFileName;    public File[] getImage() {        return image;    }    public void setImage(File[] image) {        this.image = image;    }    public String[] getImageFileName() {        return imageFileName;    }    public void setImageFileName(String[] imageFileName) {        this.imageFileName = imageFileName;    }    public String addUI(){        return "success";    }    public String execute() throws Exception{                String realpath = ServletActionContext.getServletContext().getRealPath("/images");  //获取服务端的保存文件的文件夹路径(绝对路径)        System.out.println(realpath);        if(image!=null){                                                                    //判断上传的文件是否为空            File savedir = new File(realpath);                                              //创建文件保存的目录,如果目录不存在则创建            if(!savedir.exists()) savedir.mkdirs();            for(int i = 0 ; i<image.length ; i++){                                File savefile = new File(savedir, imageFileName[i]);                        //循环得到每个文件                FileUtils.copyFile(image[i], savefile);            }            ActionContext.getContext().put("message", "上传成功");        }        return "success";    }}

    5.struts.xml文件的配置和单个文件上传没有多大的区别,如下所示:

    <struts>    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>    <constant name="struts.action.extension" value="do,action"/>    <constant name="struts.multipart.maxSize" value="10701096"/>        <package name="employee" namespace="/control/employee" extends="struts-default">        <action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">            <result name="success">/WEB-INF/page/message.jsp</result>        </action>    </package></struts>

     

strut2 多个文件上传