Multiple File Upload in Struts 2

This project will demonstrate how to create Multiple File Upload in Struts 2

  • Strust2
    • src/main/java
      • controllers.action
        • AccountAction.java
    • src
      • main
        • webapp
          • assets
            • uploads
          • WEB-INF
            • views
              • account
                • index.jsp
                • success.jsp
            • web.xml
          • index.jsp
    • pom.xml
package controllers.action;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

@Namespace("/account")
public class AccountAction extends ActionSupport implements ServletRequestAware {

    private static final long serialVersionUID = 1L;

    private File[] fileUpload;
    private String[] fileUploadContentType;
    private String[] fileUploadFileName;

    private HttpServletRequest servletRequest;

    public String[] getFileUploadContentType() {
        return fileUploadContentType;
    }

    public void setFileUploadContentType(String[] fileUploadContentType) {
        this.fileUploadContentType = fileUploadContentType;
    }

    public String[] getFileUploadFileName() {
        return fileUploadFileName;
    }

    public void setFileUploadFileName(String[] fileUploadFileName) {
        this.fileUploadFileName = fileUploadFileName;
    }

    public File[] getFileUpload() {
        return fileUpload;
    }

    public void setFileUpload(File[] fileUpload) {
        this.fileUpload = fileUpload;
    }

    @Action(value = "index", results = {
        @Result(name = SUCCESS, location = "/WEB-INF/views/account/index.jsp")
    })
    public String index() {
        return SUCCESS;
    }

    @Action(value = "save", results = {
            @Result(name = SUCCESS, location = "/WEB-INF/views/account/success.jsp")
        }, interceptorRefs = {
            @InterceptorRef(
                params = {
                    "allowedTypes", "image/png,image/gif,image/jpeg,image/jpg",
                    "maximumSize", "2097152"
                },
                value = "fileUpload"
            ),
            @InterceptorRef("defaultStack")
        }
    )
    public String save() throws Exception {

        // Get Files Information
        for (int i = 0; i < this.fileUpload.length; i++) {
            File uploadedFile = this.fileUpload[i];
            System.out.println("File Name: " + this.fileUploadFileName[i]);
            System.out.println("File Size(bytes): " + uploadedFile.length());
            System.out.println("File Type: "+ this.fileUploadContentType[i]);
            System.out.println("-----------------------");
        }

        // Save Files
        for (int i = 0; i < this.fileUpload.length; i++) {
            String filePath = servletRequest.getServletContext().getRealPath("/assets/uploads");
            File fileToCreate = new File(filePath, this.fileUploadFileName[i]);
            FileUtils.copyFile(this.fileUpload[i], fileToCreate);
        }

        return SUCCESS;
    }

    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
    }

}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body>

    <h3>Register</h3>
    <s:form method="post" namespace="/account" action="save" enctype="multipart/form-data">
        <s:file label="Photo 1" name="fileUpload" accept="image/*" />
        <s:file label="Photo 2" name="fileUpload" accept="image/*" />
        <s:file label="Photo 3" name="fileUpload" accept="image/*" />
        <s:submit value="Save All" align="left"></s:submit>
    </s:form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:forward page="account/index.html"></jsp:forward>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Learn Struts 2 with Real Apps</title>
</head>
<body>

    <h3>Photos of Account</h3>
    <c:forEach var="photo" items="${fileUploadFileName }">
        <img src="${pageContext.request.contextPath }/assets/uploads/${photo }" width="120" height="100">
    </c:forEach>

</body>
</html>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.convention.default.parent.package" value="controllers"/>

    <package name="controllers" extends="struts-default">
        <interceptors>
            <interceptor name="dateLogInterceptor" class="interceptors.DateLogInterceptor" />
            <interceptor name="timeLogInterceptor" class="interceptors.TimeLogInterceptor" />
            <interceptor name="browserInterceptor" class="interceptors.BrowserInterceptor" />
        </interceptors>
    </package>

</struts>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
            http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <display-name>Learn Struts 2 Framework with Real Apps</display-name>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
            <param-name>struts.devMode</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>struts.action.extension</param-name>
            <param-value>html</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>LearnStrutsFrameworkWithRealApps</groupId>
    <artifactId>LearnStrutsFrameworkWithRealApps</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>LearnStrutsFrameworkWithRealApps Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Struts 2 Framework -->

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.20</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-convention-plugin</artifactId>
            <version>2.5.20</version>
        </dependency>

        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-json-plugin</artifactId>
            <version>2.5.20</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>LearnStrutsFrameworkWithRealApps</finalName>
    </build>
</project>

Screenshots