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.



35 Comments

  • jawahar wrote on 8 January, 2010, 10:46

    hi viral one help can you autocompleter example in Struts2

  • jawahar wrote on 8 January, 2010, 10:47

    hi viral one help can you post autocompleter example in Struts2

  • Zubin wrote on 8 January, 2010, 16:50

    I am new to struts 2.This is really a very good example….It helped me a lot….Thanks….
    Question : How to store the File in the database(Like Oracle) ??? Can you please provide the code for it???
    Thanks in advance….

  • finosh wrote on 9 January, 2010, 11:55

    I am thankful to viral for help me in struts2

  • Arscek wrote on 10 February, 2010, 0:27

    Hello! Thanks for this tutorial, it was very helpful. I have one problem. When my form is loaded, it needs some dynamic data to be loaded from my DB(some selects, and labels). It works great if I don’t upload wrong file types, but when I try to upload a different kind of file, it doesn’t load the dynamic data. If I redirect to the action, it works fine, but then it doesn’t show the error message, this is my struts.xml, as you can see, it uses wildcards to handle method invocation:

    newTicket.jsp
    /WEB-INF/HelpDeskForms/segResponder.jsp
    /WEB-INF/HelpDeskForms/segRequester.jsp
    /WEB-INF/HelpDeskForms/segAdmSup.jsp
    /WEB-INF/HelpDeskForms/newTicket.jsp
    /WEB-INF/HelpDeskForms/detRequester.jsp
    unassignedByAreaTicket
    postCreateTicket

    ………..

  • jay wrote on 5 March, 2010, 16:20

    Hi,,, Thanks for the article….
    But im not getting output… It says…
    userImageFileName is null
    and giving NullpointerException
    Any extra code to write than you have given above..
    I think no but wat is the reason why its giving NullPointerException…….?
    Plz… Thanks in advance….

  • jay wrote on 5 March, 2010, 16:44

    System.out.println(“user Image :” + userImage);
    System.out.println(“user Image Name:” + userImageFileName);

    Both are returning null so

    File fileToCreate = new File(filePath, getUserImageFileName());
    returning NullPointerException

    any help plz….

    • Gopikrishnan wrote on 18 October, 2011, 1:42

      Hi,
      The error you have faced – “I have problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
      plz I need your help”
      can be resolved by adding the following interceptor in your struts.xml since the file upload action you are calling doesnt call the servlet class at that instance.

      Interceptor:

      example below is the one used in my application

      application/vnd.ms-excel
      <!– 10240 10KB –>
      2097152

      fileUpload.def
      Footer.jsp

  • mistersimpatiko wrote on 17 July, 2010, 10:10

    try to remove the interceptors, this works for me. but its weird… :)

  • swag01 wrote on 27 July, 2010, 8:23

    I am really enjoying this tutorial!!! Great job.

    Everything is working for me using jboss; however, I noticed that servletRequest.getRealPath…

    is coming up with a deprecation message.

    What is the replacement for this?

    Thanks again!

    • Viral Patel wrote on 27 July, 2010, 11:12

      @swag01: Thanks for pointing out this. ServletRequest.getRealPath() method has been deprecated as the same method is available in javax.servlet.ServletContext interface.

  • swag01 wrote on 28 July, 2010, 5:10

    Thanks Viral;

    I made the corrections to the FileUploadAction.java (It didn’t like the @override so I commented that out too):

    If you want to update your code with the changes, I am fine.

    //src

    • Viral Patel wrote on 28 July, 2010, 11:35

      @swag01 – Thanks for the source code. I have updated the above java code and removed call to deprecated method.

  • dWang wrote on 2 August, 2010, 10:39

    Thanks Viral;
    Where is the uploded image file?
    The tmp file is not there any more as shown on SuccessUserImage.jsp:
    User Image: D:\share\workspaceStruts2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Struts2HelloWorld\upload_4fc01309_12a30f1701e__8000_00000011.tmp
    Thanks again!
    dWang

  • vin wrote on 16 September, 2010, 18:44

    thanks a lot mr.viral patel.
    ur tutorial helped well to learn struts2.0.

  • Naks wrote on 21 September, 2010, 14:17

    ur struts.xml file donot works.
    plz kindly send some guide line

  • Larry wrote on 24 October, 2010, 4:25

    For the ServletRequest.getRealPath() deprecation I resolved with:

    servlet-api.jar
    and
    String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);

  • ali wrote on 26 January, 2011, 12:47

    hi.
    i have a problem with changing displayed message.
    my mean is when i override the messages when file size is over than my specified size like as below :
    struts.messages.error.file.too.large=Uploaded file was too large.
    in my two file
    ApplicationResource.properties , ApplicationResource_fr.properties
    only english or default message be displayed and if changing my locale it has not any effect.

  • swathi wrote on 23 February, 2011, 13:56

    hi im new to struts2.i have to write validation for file upload field.can any one help me

  • swathi wrote on 23 February, 2011, 14:06

    hi im new to struts2.i have to write validation for file upload field.can any one help me………………

  • swathi wrote on 23 February, 2011, 14:07

    hi

  • workingforjava wrote on 23 February, 2011, 17:23

    Swathi,

    please refere the previous post (Struts2 Validation Framework Tutorial with Example
    )..if u dont just reply i will give you the code.

    Regards,
    workingforjava@gmail.com

  • Bhavik wrote on 4 March, 2011, 11:30

    i am impressed in the first visit.
    hope it will solve all my problem related asynchronously file upload.

  • Chooyoon Kim wrote on 11 March, 2011, 16:07

    At last I can solve the question and errors using your valuable Tiles Example after 4 hours st\ruggle against the incomplete articles and codes posted to Korean Websites by my people. Thank you! Pls post the more examples….. .

  • shiva wrote on 18 July, 2011, 21:59

    any one help how to attach file and store that file in database with example

  • adbeng wrote on 29 July, 2011, 3:57

    I have problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
    plz I need your help

  • kannan wrote on 29 July, 2011, 18:02

    Yes, I also have that same problem with String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”); .It allways return null .And I get a java.lang.NullPointerException
    plz I need your help

    • adbeng wrote on 1 August, 2011, 8:11

      hii kannan pay attention to FileUploadAction class :you have just to copy as its write here and its work very well.Good luck .

  • Pradeep wrote on 14 October, 2011, 18:19

    Hi,
    Can you help to debug the following error in my eclipse deployment. I have downloaded he source code and added the binaries as mentioned here.
    I’m getting the following warning

    WARNING: No configuration found for the specified action: ‘userImage’ in namespace: ”. Form action defaulting to ‘action’ attribute’s literal value.
    Oct 14, 2011 3:14:57 PM org.apache.struts2.dispatcher.Dispatcher getSaveDir
    INFO: Unable to find ‘struts.multipart.saveDir’ property setting. Defaulting to javax.servlet.context.tempdir

    and the page gives following error

    HTTP Status 404 – /StrutsHelloWorld/userImage

    ——————————————————————————–

    type Status report

    message /StrutsHelloWorld/userImage

    description The requested resource (/StrutsHelloWorld/userImage) is not available.

  • GV wrote on 3 November, 2011, 9:36

    Hi Pradeep,

    For testing,In web.xml instedof Login.jsp update it to UserImage.jsp and test updaload process.

  • ck wrote on 26 December, 2011, 20:39

    Thanks so much Viral, with your tutorial, it help me to study struts2 very quick. Thank you very much

  • Arun wrote on 19 January, 2012, 11:56

    the program is working fine. but pls tell me where the file is getting uploaded in the server. pls tell me how to change the file path where i upload the file in the server. thanks in advance. you are doing a great job.

  • Preeti wrote on 20 January, 2012, 15:11

    Hi,viral this was a very nice tute..one help i need ,actually needs to design a dojo tree with the help of json and this json should be from action class of struts 2.can u help me out…sa soon as posible…thanks

  • eknath wrote on 6 February, 2012, 12:26

    Its Fine tutorial But i want to save that image to mysql database can u help me with the code

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.