Viral Patel is a keen technology blogger and enthusiast. Working with a software company, he uses his leisure time to learn and explore emerging areas in tech world. His passion for technology has motivated him from creating an operating system to writing tutorials/articles on Java, JavaEE, Spring, Hibernate, Struts, jQuery, PHP. Visit the website http://viralpatel.net for a wide range of articles and tutorials on these topics. Viral has posted 13 posts at DZone. View Full User Profile

Struts 2 Tutorial: Struts 2 File Upload and Save Tutorial with Example

01.19.2010
| 80124 views |
  • submit to reddit

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.

Struts 2 Tutorial List

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

Published at DZone with permission of its author, Viral Patel.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Prasad koti replied on Tue, 2010/08/31 - 2:31am

Hi Viral,

The tutorial is good.

I need some more stuff in this like

I needed the code for storing the images to mysql db using struts.

It would be better if show same example using Hibernate , struts and Mysql.

 Thanks in advance

Regards,

Prasad

 

Gaurav Gupta replied on Tue, 2010/09/14 - 4:59am

Hi i have read all the examples above mentioned. These are very useful in setting and using a new project... Thanks a lot dear. Gaurav gauravjirss2@gmail.com

Duminda Duleep replied on Mon, 2011/06/13 - 12:58am

FileUploadAction class in "import javax.servlet.http.HttpServletRequest;" line give The import javax.servlet.http.HttpServletRequest cannot be resolved error in eclipse anyone have idea what jar filemissing?

Duminda Duleep replied on Tue, 2011/06/14 - 1:25am

This good tutorials. If you try this tutorials make sure "Required JAR file" is given version don't use new jar files. i got many runtime error when i use new struts lib jar file.

Gopi Krishnan replied on Mon, 2011/10/17 - 3:36pm in response to: Duminda Duleep

Add servlet-api.jar as an external jar from tomcat path for eg - D:\apache-tomcat-7.0.21\lib in your eclipse IDE. Your problem "javax.servlet.http.HttpServletRequest cannot be resolved error in eclipse" will get resolved. Its working fine for me. Please  make note tht servlet-api.jar should not be add under WEB-INF/lib

 

 

Rajagopal Rajam... replied on Fri, 2012/03/23 - 7:34am

This works only if we have

<s:form action="userImage.action" method="post" enctype="multipart/form-data">

 in UserImage.jsp

Ligz Anghao replied on Mon, 2013/09/09 - 2:30am

plz add the following dependency to your pom.xml if you are using maven:


  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.4</version>
  </dependency>


Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.