File Upload is one of the common tasks of a web application and Struts 2 provides built-in feature for multiple files upload through FileUploadInterceptor. Interceptors are cross cutting concerns or common concerns like Logging; for more information on Interceptors please refer to Struts2 Interceptors

FileUploadInterceptor(for more information go to File upload interceptors) is configured in the struts-default package that we usually extend in Struts 2 package configuration. FileUploadInterceptor also provide options to set the maximum file size limit, allowed file types and extensions that can be uploaded to the server. Struts 2 provide option to configure the maximum file size limit through struts.multipart.maxSize variable. This comes handy to set the limit to upload files incase of multiple files uploading in a single request.
FileUploadInterceptor intercepts the request with enctype as “multipart/form-data” and automatically saves the file in the temp directory and provide useful reference to File, file name and file content type to action classes to save the file at specified location.

We will look into the implementation through a sample Struts 2 project where we will upload multiple files.
Please make sure that the following jars exist in the classpath
file upload example in struts
Let’s look at different parts of the application for uploading multiple files.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""
    id="WebApp_ID" version="3.0">


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Multiple File Upload Example</title>
    <s:if test="hasActionErrors()">
        <s:actionerror />
    <s:if test="hasActionMessages()">
        <s:actionmessage />
    <s:form action="uploadMultipleFile" method="post" enctype="multipart/form-data">
        <s:file label="File1" name="file"></s:file>
        <s:file label="File2" name="file"></s:file>
        <s:file label="File3" name="file"></s:file>
        <s:file label="File4" name="file"></s:file>
        <s:submit value="Upload"></s:submit>


The important points to note in single.jsp are enctype (multipart/form-data), file element name (file) and action (uploadSingleFile).

Before we move to action class implementation, let’s look at the struts.xml configuration file.


<?xml version="1.0" encoding="UTF-8"?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    <!-- upload max file size limit -->
    <constant name="struts.multipart.maxSize" value="10485760" />
    <package name="default" namespace="/" extends="struts-default">
        <action name="uploadMultipleFile" class="in.sblog.actions.MultipleFileUploadAction">
            <param name="filePath">file</param>
            <result name="success">/multiple.jsp</result>
            <result name="input">/multiple.jsp</result>
            <interceptor-ref name="defaultStack">
                <param name="maximumSize">10485760</param>
                <param name="allowedTypes">text/plain,image/jpeg,image/png,image/gif,image/pjpeg</param>


Notice that I have set the maximum file size limit in a single request to 10 MB by setting the value of struts.multipart.maxSize to 10*1024*1024.

FileUploadInterceptor default limit for single file size is 2 MB, so I am overriding it for uploadSingleFile action. I am using defaultStack with params maximumSize (10MB) and allowedTypes (text/plain,image/jpeg,image/png,image/gif,image/pjpeg) for fileUpload interceptor.

Now we are ready to look into the action class implementation.

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;
public class MultipleFileUploadAction extends ActionSupport implements
        ServletContextAware {
    private static final long serialVersionUID = 1L;
    private File[] file;
    private String filePath;
    private String[] fileFileName;
    private ServletContext servletContext;
    public File[] getFile() {
        return file;
    public void setFile(File[] file) {
        this.file = file;
    public String getFilePath() {
        return filePath;
    public void setFilePath(String filePath) {
        this.filePath = filePath;
    public String[] getFileFileName() {
        return fileFileName;
    public void setFileFileName(String[] fileFileName) {
        this.fileFileName = fileFileName;
    public ServletContext getServletContext() {
        return servletContext;
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    public String execute() throws Exception {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        File dir = new File(servletContext.getRealPath(""));
        System.out.println("servletContext.getRealPath(\"\"): "
                + servletContext.getRealPath(""));
        if (!dir.exists()) {
        try {
            for (int i = 0; i < file.length; i++) {
                String targetPath = dir.getPath() + File.separator
                        + fileFileName[i];
                System.out.println("targetPath: " + targetPath);
                File f = new File(targetPath);
                fileInputStream = new FileInputStream(file[i]);
                fileOutputStream = new FileOutputStream(f);
                int c;
                while ((c = != -1) {
        } catch (Exception e) {
            addActionError("Error occurred during uploading the file!");
            return INPUT;
        } finally {
            if (fileInputStream != null) {
            if (fileOutputStream != null) {
        addActionMessage("File(s) successfully uploaded!");
        return SUCCESS;
    public void validate() {
        if (null == file) {
            addActionMessage("You must select at least one file!");


Notice that action class is implementing ServletContextAware interface that contains overridden method setServletContext(). This is done to get the ServletContext reference in action class and use it to get the web application root directory. This will be used in saving the file from temp directory to another directory inside web application.

The filePath parameter defined for uploadMultipleFile action, hence we have setFilePath() method in the above class. This method is used by Struts 2 params interceptor to read the params configured in struts.xml file and invoke it’s setter method.

The three variables that are set by file upload and params interceptors are File, file name and content type. If the file element name in request is “f” then these variables should be – File f, String fContentType and String fFileName. Since our single.jsp file element name is “file”, we have variables file, fileFileName and fileContentType with their getter and setters. Here I have used array for file and fileName because of multiple files wil be uploaded.

Now when we execute the file upload action then we get the response.

Run the application in server
file upload example in struts
If you do not select any file and click on Upload button then you will get error message
file upload example in struts

Now if you select files and click on Upload button and if the files successfully uploaded then you will get successful message otherwise you will get error message
file upload example in struts

Now files are successfully uploaded to the location : <Eclipse workspace>\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\struts2-file-upload\<uploaded files>

Thanks for your reading. Please do not forget to leave a comment.


Leave a Reply

Your email address will not be published. Required fields are marked *