Struts 2 File Upload Example

In this example you will learn how to do file upload with the help of the built-in FileUploadInterceptor. To do this first we need to get the file form the user. We use the Struts 2 tags to build our form. The encoding type of the form should be set to multipart/form-data and the HTTP method should be set to post. The index.jsp page contains the following code.

Create two JSP file in WebRoot folder. index.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to success.jsp file where File details will be displayed. Copy following code into it.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<title>Upload User Image</title>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
    <s:file name="userImage" label="User Image" size="10"/>
    <s:submit value="Upload" align="center" />

There are couple of points worth noting in the above example. First of all, the form's enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form's action method upload and the name of the file upload field - which is userImage. We need this information to create the action method and the struts configuration.

Next let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success. 

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<title>Success: Upload User Image</title>
    <h2>Struts2 File Upload Example</h2>
    User Image: <s:property value="userImage"/>
    Content Type: <s:property value="userImageContentType"/>
    File Name: <s:property value="userImageFileName"/>
    Uploaded Image:
    <img src="<s:property value="userImageFileName"/>"/>
Following will be the result file error.jsp in case there is some error in uploading the file:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<title>File Upload Error</title>
There has been an error in uploading the file.
Create action class:
Next let us create a Java class called which will take care of uploading file and storing that file at a secure location:
package com.dineshonjava.struts2.action.upload;


import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

 * @author Dinesh Rajput
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
 private static final long serialVersionUID = 1L;
 private File userImage;
 private String userImageContentType;
 private String userImageFileName;
 private HttpServletRequest servletRequest;
 public String execute() {
  try {
      String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
      System.out.println("Server path:" + filePath);
      File fileToCreate = new File(filePath, this.userImageFileName);
      FileUtils.copyFile(this.userImage, fileToCreate);
  } catch (Exception e) {
      return INPUT;
  return SUCCESS;
 public File getUserImage() {
  return userImage;
 public void setUserImage(File userImage) {
  this.userImage = userImage;
 public String getUserImageContentType() {
  return userImageContentType;
 public void setUserImageContentType(String userImageContentType) {
  this.userImageContentType = userImageContentType;
 public String getUserImageFileName() {
  return userImageFileName;
 public void setUserImageFileName(String userImageFileName) {
  this.userImageFileName = userImageFileName;
 public void setServletRequest(HttpServletRequest servletRequest) {
  this.servletRequest = servletRequest;
In above class file we have declared few attributes:
  • private File userImage; -> This will store actual uploaded File
  • private String userImageContentType; -> This string will contain the Content Type of uploaded file.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName.
Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.

Configuration files:
Following are the Struts2 configuration properties that control file uploading process:
<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   <constant name="struts.devMode" value="true" />
   <package name="upload" extends="struts-default">
      <action name="userImage" class="com.dineshonjava.struts2.action.upload.FileUploadAction">
      <interceptor-ref name="fileUpload">
         <param name="maximumSize">2097152</param>
         <param name="allowedTypes">
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">success.jsp</result>
    <result name="input">index.jsp</result>
     <result name="error">error.jsp</result>
Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg).

The file upload interceptor also does the validation and adds errors, these error messages are stored in the file. The values of the messages can be overridden by providing the text for the following keys:
  1. struts.messages.error.uploading – error when uploading of file fails
  2. struts.messages.error.file.too.large – error occurs when file size is large
  3. struts.messages.error.content.type.not.allowed – when the content type is not allowed
Following is the content of web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">

Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat's webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/doj/index.jsp.
This will give you following screen:
Struts 2 File Upload Example

Image Upload Screen in case of error-

Struts 2 File Upload Example

Image Upload Screen on success-

Struts 2 File Upload Example

Another Image Upload Screen on success-

Struts 2 File Upload Example

Download Source Code+Libs

<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment