Wednesday, July 1, 2009

Uploading a file with Struts 2

Uploading a file with Struts 2 is really simple with the help of the FileUploadInterceptor. The steps required to upload a file using Struts 2 are:

Step 1

Create the Struts 2 Action class. In our example we have called it

An example of an action to upload a file:


import com.opensymphony.xwork2.Action;

* Uploads a file using Struts 2
* @author Armindo Cachada
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 12323232L;
private File file;
private String fileFileName;
private String fileContentType;

public String execute() {

return Action.SUCCESS;

public File getFile() {
return this.file;

public void setFile(File file) {
this.file = file;

public void setUpload(File file) {
this.file = file;
* This method is called by the action.
* Here you can do whatever you want with the uploaded file
public String upload() throws IOException {
File uploadedFile =this.getFile();
// you can do whatever you want with the file
return Action.SUCCESS;

public String getFileFileName() {
return fileFileName;

public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;

public String getFileContentType() {
return fileContentType;

public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;

public String getFileUrl() {
return fileUrl;

public void setFileUrl(String fileUrl) {
this.fileUrl = fileUrl;

Step 2

Create the action in struts.xml

<action name="fileUpload" class="" method="upload">
<result>/success.jsp </result>
<result type="error">/upload.jsp</result>

Step 3

Create the jsp. For example:

Please select the file you want to upload:

<s:form action="fileUpload" method="post" enctype="multipart/form-data" theme="simple">
<s:actionerror cssClass="errorMessage"/>
<s:fielderror cssClass="error"/>
<s:file name="upload" label="File"/>

Step 3

The default maximum file size that struts 2 allows you to upload is only 2 megabytes. You can increase this size by specifying in the struts.multipart.maxSize. This value is in bytes.
For example:


Finally you can download the code for this example here.

Note that I didn't include the required struts2 library files with the example.
The files you need are:


Click here to learn how to upload a file with Adobe Flex


SF Building said...

Please include Flex code also.

Armindo Cachada said...

You can find the information you need here: