Struts 2 File Upload and Save Tutorial with Example

Welcome to Part-6 of 7-part series of Struts2 Framework. In previous part we went through basics of Struts2 Interceptors. Also we created a custom interceptor and integrated it through Struts2 application.

It is strongly recommended to go through previous articles in case you new to Struts2 Framework.

Today we will see how to do File Upload in Struts2. We will use Struts2 built-in FileUploadInterceptor in our example to upload the file. 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 file

Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files.
struts2-file-upload-jar-files

Getting Started

In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package net.viralpatel.struts2.
FileUploadAction.java

package net.viralpatel.struts2;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
		ServletRequestAware {
	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) {
			e.printStackTrace();
			addActionError(e.getMessage());

			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;
	}

	@Override
	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.

The JSPs

Create two JSP file in WebContent folder. UserImage.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 SuccessUserImage.jsp file where File details will be displayed. Copy following code into it.
UserImage.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>

<body>
<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" />
	<s:submit value="Upload" align="center" />
</s:form>
</body>
</html>

SuccessUserImage.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
	<h2>Struts2 File Upload Example</h2>
	User Image: <s:property value="userImage"/>
	<br/>
	Content Type: <s:property value="userImageContentType"/>
	<br/>
	File Name: <s:property value="userImageFileName"/>
	<br/>
	Uploaded Image:
	<br/>
	<img src="<s:property value="userImageFileName"/>"/>
</body>
</html>

Struts.xml entry

Add following entry for FileUploadAction class to struts.xml file.

		<action name="userImage"
			class="net.viralpatel.struts2.FileUploadAction">
			<interceptor-ref name="fileUpload">
				<param name="maximumSize">2097152</param>
				<param name="allowedTypes">
					image/png,image/gif,image/jpeg,image/pjpeg
				</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="success">SuccessUserImage.jsp</result>
			<result name="input">UserImage.jsp</result>
		</action>

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 struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:

  • struts.messages.error.uploading – error when uploading of file fails
  • struts.messages.error.file.too.large – error occurs when file size is large
  • struts.messages.error.content.type.not.allowed – when the content type is not allowed

That’s All Folks

Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp
Image Upload Screen
struts2-file-upload-example

Image Upload Screen in case of error
struts2-file-upload-error
Image Upload Screen on success
struts2-file-upload-success

Download Source Code

Click here to download Source Code without JAR files (20KB)

Moving On

Struts2 makes life very easy. It was like a piece of cake to implement File Upload with Struts2. In next part we will see Struts2 Ajax Example.



83 Comments

  • HP 13 November, 2012, 21:35

    userImageFileName null please help me?

  • Nagbhushan 11 December, 2012, 19:25

    Getting big Null Pointer Exception at line:

    fileToCreate = new File(filePath, this.htmlFileName);

    However userImage value in debug mode is :

    “D:XYZ\workspace_4\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\HTMLToJSP\upload__1d70e13a_13b8a3f0bbd__8000_00000000.tmp”

  • Sandaruwan 22 December, 2012, 0:03

    I got that null issue all the time using glassfish 3.1.2
    I switched to tomcat server and it worked fine.
    I just changed server to glassfish 3.1.2.1 version and it also worked fine..

    I think the issue was with the server.
    Just to let u know.. Cheers..

    • bhavesh 15 February, 2013, 19:03

      i have executed it …with the code ..
      the problem is when i execute the UserImage.jsp after giving every details
      and when i click on submit button ,then it goes to SuccessUserImage where it dosnt gives the oproper output …evry fields is empty …(NO OUTPUT)
      SOME1 plz help me,,,,,,,

  • Kumar 2 January, 2013, 14:48

    when I am Giving Image file It Is working, but when i am not giving any image, it is not showing error message in UserImage.jsp, But it is returning the UserImage.jsp..
    Plz tell me how to show error message in UserImage.jsp

    Thanx In Advance

  • modtanoi 3 January, 2013, 16:28

    where is photo after upload fie?

  • Ahmed 12 February, 2013, 19:01

    I am getting the filename, contentType empty, and having null exception at
    File filetocreate = new File(filepath, fileName)
    fileName value is null in the action.
    thought the filename gets uploaded and displays the file name in jsp file.

    • Ahmed 12 February, 2013, 20:14

      Oh Just solve the filename null axception in the action.

      the solution is:

      whatever you name your file variable, let say
      privare File fileUpload;

      the ContentType and FileName should be prefixed by the “fileUpload” like below:
      private String fileUploadContentType;
      private String fileUploadFileName

      hope this will help those who are having same problem

  • Rahul 20 February, 2013, 17:35

    Hi Viral –
    Have one doubt , is it is possible to configure file upload maximumSize value by programatically. because I have to configure different fileupload maxSize limit for different roles ( users ).
    If yes please give some ideas.

    Is it is possible to override fileUpload interceptor .

  • devika 21 February, 2013, 14:10

    I want the file to be saved in the directory with a seperate file extension.Like if i uploaded a .jpeg or .gif file i want both to be saved in .jpeg format.Is it possible??How?

  • joejokelly@gmail.com 12 March, 2013, 2:08

    Thanks Viral,
    Very good tutorial.

    Joe.

  • saurabh 14 March, 2013, 19:27

    Thank you for sharing code this work for me
    I have 1 question how to change by default the path of image upload?

  • rasmi 15 March, 2013, 16:02

    how can i change the path of saved file???or can i save the uploaded file into folder of my application??

  • Sanjoy Roy 27 April, 2013, 15:08

    When i run your above code , i get the follwoing error :

    The type UploadFile must implement the inherited abstract method ServletRequestAware.setServletRequest(HttpServletRequest

    I need ur help urgent !
    Thanks,
    Sanjoy Roy

    • Mel 27 June, 2013, 9:19
       
      public class SampleStrutsAction implements ServletRequestAware{
      private HttpServletRequest request;
      
      @Override
      	public void setServletRequest(HttpServletRequest request) {
      		// TODO Auto-generated method stub
      		this.request = request;
      	}
      }
      
    • Mel 27 June, 2013, 9:20
       
      public class SampleStrutsAction implements ServletRequestAware{
               private HttpServletRequest request;
      
               /**
               * You need to declare this method when implementing ServletRequestAware
               */
              @Override
      	public void setServletRequest(HttpServletRequest request) {
      		// TODO Auto-generated method stub
      		this.request = request;
      	}
      }
      
  • Latifa 4 May, 2013, 14:55

    thanks for this tutoriel, how can i adapt the code in order to upload other file (pdf,txt,…)?

  • lakhan 30 May, 2013, 19:20

    hi.its very helpful tutorial…Thanks Viral….

  • calin 11 August, 2013, 16:49

    was is such a big deal to upload those da*n JARs ?
    not working for me

  • Balram 11 September, 2013, 16:23

    @Viral : thanks for great tutorials …
    please also update source code which has been given for download.

  • anu 27 September, 2013, 17:50

    thanx for this tutorial and please give tutorials for downloading a file.

  • Vikrant deshmukh 28 October, 2013, 13:14

    Sir, is it possible to upload video or audio file using this ???
    what i need to do this ?please help me its urgent

    Regards
    vikrant Deshmukh

  • Sivaji A 14 November, 2013, 10:59

    Please help if the file size is larger.
    I am getting no action defined error.

  • prashanth 19 December, 2013, 16:01

    Hi everyone,
    Can anyone tell me how to fix “content type not allowed” error.

  • ranjeet 15 March, 2014, 12:54

    sir plz tell me where to get the jar files in tiles project

  • swapna 2 June, 2014, 15:11

    Hi ,

    If I use some other names like filepath and copied file instead of userImage and userImageFileName then why my program is not working.Do there is any connection with the names in the action class and the interceptors.I have used the same names in the jsps also.

  • Ravi 11 June, 2014, 1:03

    hi sir .
    String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);

    here i want to save location in my project files how can i set this path
    i want “WebContent/” like This
    And
    i don’t want to this type of locations “E:/myphotos/”

    thanks

  • Arpit 25 June, 2014, 15:36

    good tutorial

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *