File Upload in struts 2

This is 6 of 8 part of struts 2 tutorial.In this tutorial we will learn how to upload file to server in struts 2 and also how save uploaded file on directory of server machine.

Tutorial Content:

Part-1:Introduction to struts 2
Part-2:configuring struts 2 in eclipse
Part-3:Struts 2 hello world example
Part-4:Login page with validation in struts 2
Part-5:Struts 2 interceptors with example
Part-6:File upload in struts 2
Part-7:Struts 2 ajax example
Part-8:Struts 2 spring 3 integration example 

Struts 2 file upload component can be used to upload mulitpart file in struts 2 application.Struts 2 utilizes in built File upload interceptor for uploading files in struts 2 application.The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element.

Required jar :
We need to have 1 jar common-io.jar in your classPath.In configuring struts 2 in eclipse post,we have already added jar in classPath.
Create project named "fileUploadInStruts2".For configuring struts 2 in your eclipse ide please refer configuring struts 2 link.

Project stucture:

Action class: 

For adding file uploading functionality in struts 2,We will create action class named
Create file under src folder in package org.arpit.javaPostsForLearning.

copy following content in

package org.arpit.javaPostsForLearning;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements ServletRequestAware {

    private File toBeUploaded;
    private String toBeUploadedFileName;
    private String toBeUploadedContentType;
    private HttpServletRequest servletRequest;
    public String execute()
         String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
         File fileToCreate = new File(filePath, this.toBeUploadedFileName);

         try {
            FileUtils.copyFile(this.toBeUploaded, fileToCreate);
        } catch (IOException e) {
        return SUCCESS;
    public File getToBeUploaded() {
        return toBeUploaded;
    public void setToBeUploaded(File toBeUploaded) {
        this.toBeUploaded = toBeUploaded;
    public String getToBeUploadedFileName() {
        return toBeUploadedFileName;
    public void setToBeUploadedFileName(String toBeUploadedFileName) {
        this.toBeUploadedFileName = toBeUploadedFileName;
    public String getToBeUploadedContentType() {
        return toBeUploadedContentType;
    public void setToBeUploadedContentType(
            String toBeUploadedFileNameContentType) {
        this.toBeUploadedContentType = toBeUploadedFileNameContentType;
    public void setServletRequest(HttpServletRequest servletRequest) {
Now we have declared three attributes here

 private File toBeUploaded  //Actual file to be uploaded
 private String toBeUploadedFileName // file name of actual file to be uploaded
 private String toVeUploadedContentType  // content type of actual file to be uploaded

We have provided getters and setters for above attributes.So struts 2 automatically set these value according to file being uploaded.
For example if your file name is "sampleFile" then struts 2 interceptor add three parameters to request.
Three parameters are:

you can notice here that we have given our action class attributes in same format so it will automatically set these attributes according to file being uploaded.

One more thing is that we have implemented "ServletRequestAware" interface in our action class
This is to get ServletRequest object.This request object is required to get path of server machine where file is to be uploaded.


We will create two jsp files here.fileUpload.jsp will display form for uploading file.On clicking on upload button,File will be saved on server machine and request will be forwarded to uploadSucceed.jsp which will render fileName,content type and uploaded image.


Create fileUpload.jsp under WebContent folder.
Copy following content to fileUpload.jsp.

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%@taglib uri="/struts-tags" prefix="s"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>file upload page</title>
<body bgColor="lightblue">
<s:form action="fileUpload" method="post" enctype="multipart/form-data">
    <s:file name="toBeUploaded" label="Choose file to upload" />
    <s:submit value="Upload" align="center"/>

We have used <s:file> tag for file upload interface.

Create jsp named "uploadSucceed.jsp" under WebContent folder.
Copy following content into uploadSucceed.jsp.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<%@taglib uri="/struts-tags" prefix="s"%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload Successful</title>
<s:head />
File Name :
<s:property value="toBeUploadedFileName"></s:property>
Content type:
<s:property value="toBeUploadedContentType"></s:property>
User file :
<s:property value="toBeUploaded"></s:property>
Uploaded file:
<img src="<s:property value="toBeUploadedFileName"/>"></img>


Create struts.xml under src folder.
Copy following content to struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <package name="default" extends="struts-default" namespace="/">
        <action name="fileUpload" class="org.arpit.javaPostsForLearning.FileUploadAction">
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">1048576</param>
                <param name="allowedTypes">
            <interceptor-ref name="defaultStack"></interceptor-ref>
            <result name="success">uploadSucceed.jsp</result>
            <result name="input">fileUpload.jsp</result>


It is same as in previous posts except that we have changed welcome file to "fileUpload.jsp"
Copy following content into web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns=""


 <url-pattern>/*</url-pattern>    </filter-mapping>



Run project:

Right click on project ->run as->run on server
copy resultant url(http://localhost:8080/fileUploadInStruts2/) to your browser.

Now we will browse here text file and click upload.Following screen will appear

Now again copy http://localhost:8080/fileUploadInStruts2/ url to your browser and press enter
you will get first screen again.We will browse image file named "nature.jpeg" and click on upload.
you will get following screen

Source code:

Source:Download without jars files 
Source + lib: Download with jars files

Now in next post,we will write struts 2 ajax example.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012