struts2--多文件上传

index.jsp

    此处name属性的值必须保持相同

  <s:form action="demo03/uploadsfile" method="post" enctype="multipart/form-data">
    <s:file name="files" label="File1"/>
    <s:file name="files" label="File2"/>
    <s:file name="files" label="File3"/>
    <s:submit/>
  </s:form>

struts.xml

<!--设置允许上传文件的总大小-->
<constant name="struts.multipart.maxSize" value="20971520000"/>
<action name="uploadsfile" class="cn.yang.action.UploadsAction">
     <result name="success">/jsps/success.jsp</result>
     <result name="input">/jsps/fail.jsp</result>
     <!--配置拦截器-->
     <interceptor-ref name="fileUpload">
                 <!--允许上传文件的类型-->
                <param name="allowedTypes">
                    text/plain
                </param>
                <!--允许的上传文件的扩展名-->
                <param name="allowedExtensions">
                    .txt
                </param>
                <!--允许上传的单个文件的最大值-->
                <param name="maximumSize">
                    2097152000
                </param>
            </interceptor-ref>
     <interceptor-ref name="defaultStack"/>
</action>

UploadsAction.java

    /*此处跟单个文件上传类似,只是将数据类型改成数组类型了*/
    private File[] files;
    private String[] filesContentType;//属性名格式固定([File]+ContentType)
    private String[] filesFileName;//属性名格式固定([File]+FileName)

    public File[] getFiles() {
        return files;
    }

    public void setFiles(File[] files) {
        this.files = files;
    }

    public String[] getFilesContentType() {
        return filesContentType;
    }

    public void setFilesContentType(String[] filesContentType) {
        this.filesContentType = filesContentType;
    }

    public String[] getFilesFileName() {
        return filesFileName;
    }

    public void setFilesFileName(String[] filesFileName) {
        this.filesFileName = filesFileName;
    }

    @Override
    public String execute() throws Exception {
        ServletContext context = ServletActionContext.getServletContext();
        String path =  context.getRealPath("/upload");
        /*此处与单文件上传不同的是变成了多了个for循环*/
        for (int i=0;i<files.length;i++){
            File file = new File(path,filesFileName[i]);
            FileUtils.copyFile(files[i],file);
        }
        return SUCCESS;
    }


你可能感兴趣的:(struts2--多文件上传)