Pages Navigation Menu

Coding is much easier than you think

File Upload Example in Struts 2

File Upload Example in Struts 2

 
In Struts 2 file uploading can done with the help of built-in FileUploadInterceptor. We use <s:file> tag to create a file upload component, which allow users to select file from their local disk and upload it to the server. The encoding type of the form should be set to multipart/form-data and the HTTP method should be set to post. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element. Then it adds the following parameters to the request
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
(assuming the uploaded file name is uploadDoc).

  • [uploadDoc]File – Will store the actual uploaded File
  • [uploadDoc]ContentType : This String will store the content type of the file
  • [uploadDoc]FileName : This String will store the actual name of the uploaded file (not the HTML name)

In the action class you can get the file, the uploaded file name and content type by just creating getter and setters.
 
For example

private File uploadDoc;

This will store actual uploaded File

private String uploadDocFileName;

This string will contain the file name of uploaded file.

private String uploadDocContentType;

This string will contain the Content Type of uploaded file.
 
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

 
Do read :

 

Parameters

 
You can use the following parameters to control the file upload functionality.

  • maximumSize This parameter is optional. The default value of this is 2MB.

Example:

 <param name="maximumSize">1024000</param>

Note:

You can also set the upload file size using the following code

<constant name="struts.multipart.maxSize" value="20097152" />

  • allowedTypes This parameter is also optional. It allows you to specify the allowed content type.

Note:

  • To upload txt file
 
<param name="allowedTypes"> text/plain </param>
  • To upload PDF files
 
<param name="allowedTypes"> application/pdf</param>

Recommended reading

 

Folder Structure

 
File upload in struts 2
 

Action class

 
FileUploadAction.java
 

package com.simplecode.action;

import java.io.File;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private File uploadDoc;
	private String uploadDocFileName;
	private String uploadDocContentType;

    public String execute() {
	return SUCCESS;
	}

	public File getUploadDoc() {
		return uploadDoc;
	}

	public void setUploadDoc(File uploadDoc) {
		this.uploadDoc = uploadDoc;
	}

	public String getUploadDocFileName() {
		return uploadDocFileName;
	}

	public void setUploadDocFileName(String uploadDocFileName) {
		this.uploadDocFileName = uploadDocFileName;
	}

	public String getUploadDocContentType() {
		return uploadDocContentType;
	}

	public void setUploadDocContentType(String uploadDocContentType) {
		this.uploadDocContentType = uploadDocContentType;
	}	
}

 

JSP Page

 
fileupload.jsp
 

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>file upload page</title>
</head>
<body>
	<h3>Struts 2 file upload example</h3>
	<s:form action="fileUpload" method="post" enctype="multipart/form-data">
	<s:file name="uploadDoc" label="Choose file to upload" />
	<s:submit value="upload" align="center" />
</s:form>
</body>
</html>

 
uploadSuccess.jsp
 

<%@taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<title>Upload Successful</title>
<s:head />
</head>
<body>

<h3>Struts 2 file upload example</h3>
 File Name :   <s:property value="uploadDocFileName"></s:property><br /> 
 Content type: <s:property value="uploadDocContentType"></s:property><br /> 
 User file :   <s:property value="uploadDoc"></s:property>
</body>
</html>

 

struts.xml

 
Make sure you have done action mapping properly in struts.xml file. An example of this is given below,

<struts>
<package name="" namespace="/jsp" extends="struts-default">
<action name="fileUpload" class="com.simplecode.action.FileUploadAction" >
	<interceptor-ref name="defaultStack"></interceptor-ref>
	<interceptor-ref name="fileUpload">
            <param name="maximumSize">1024000</param>
            <param name="allowedTypes">application/pdf</param>
	</interceptor-ref>
	<interceptor-ref name="validation">
		<param name="excludeMethods">input,back,cancel,browse</param>
	</interceptor-ref>
	<interceptor-ref name="workflow">
		<param name="excludeMethods">input,back,cancel,browse</param>
	</interceptor-ref>
	<result name="success">/jsp/uploadSuccess.jsp</result>
	<result name="input">/jsp/fileUpload.jsp</result>
</action>
</package>

</struts>

 

Demo

 

 http://localhost:8089/Struts2_FileUpload/

File upload example
 

Error message prompts if you upload a file which is more than 10kb, or not a text file.

 
File upload error

 
The uploaded file will be treat as a temporary file, with a long random file name, upload__376584a7_12981122379__8000_00000010.tmp. This file will be stored some where in the metadata directory
 
struts 2 File upload
 

Note:

In order to save the .tmp file in a desired location ,which you wish , then use the following code in your struts.xml

 
<constant name="struts.multipart.saveDir" value="D:/your folder"/>

 
To more about overriding these default file upload error message, click on- Override struts 2.x file upload messages

 
Caution :
 
The problem with above code snippet is, you cannot see the uploaded file in the target folder. Also the file uploaded wont have any proper extension, instead it will have the extension as .tmp.
 

Struts 2 – Upload File to Desire Folder Location

 
So in-order to upload and save a file in target space and in-order to have a file with proper extension, i.e .pdf , .doc etc, we should use the following code snippet in the action class’s execute method.
 
Modified execute method
 

public String execute() 
{
// Location to store the uploaded file in our desired path
String targetPath = "D:/file target/";
File fileToCreate = new File(targetPath, uploadDocFileName);
	try
	{
		FileUtils.copyFile(this.uploadDoc, fileToCreate);
	}
	catch (IOException e) 
	{
		addActionError(e.getMessage());
	}
	return SUCCESS;
}

 

dwd2
Zip file – FileUpload.zip
War file – FileUpload.war

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Cherukuri

    This will not work.. Where is the logic for storing or copying the files to the server loaction

    • http://www.simplecodestuffs.com/ Mohaideen Jamil

      In case of Struts2 its FileUploadInterceptor will take care of storing the file into server location, you dont need to write any logic for it.

      How ever if you still want a your logic to store file then refer the code under Modified execute method

  • SKR

    how can i get context path .when we deploye project in apache in any directory ,file upload is not working

    • Chandan Paul

      Is it possible to show image in jsp which is stored outside of my project folder. If yes then how..

  • SKR

    how can i get context path .when we deploye project in apache in any directory ,file upload is not working