File upload and copy code using struts 2 example.

If you are using struts 1.2, then go through my earlier tutorial how to upload a file using struts 1.2. In struts 2.0 or 2.1.x, s:file tag is used to upload a file. In this tutorial, let us see that how to configure and upload a file to server using struts 2.x in easy steps. Some additional libraries are required to handle parsing of uploaded files. Add the below libraries to your class path if you don’t have already.

1. Commons-FileUpload 1.2.1 or above
2. Commons-IO 1.3.2 or above

Note : If you are using struts 2.0 then use Commons-FileUpload 1.1.1 and Commons-IO 1.0

Steps to upload a file.

Let us create a sample struts project called Struts2Sample.

Step 1. Design a web form for uploading a file. Use s:file tag that enables the user to browse and select a file from the local machine. You need to set the encoding type of form to “multipart/form-data” and specify the HTTP method as “post”. The code of the JSP is as follows.

fileUpload.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	<title>fileUpload</title>
	</head>
		<body>
		<s:form   action="processFileUpload" method="post" enctype="multipart/form-data" >
			 <tr>
			 <td ><s:file name="file1" label="Select the file to upload:"/></td>
			 </tr>
			 <tr><td align="center"> <s:submit/></td>
			 </tr>
		</s:form>
		</body>
</html>

Step 2 : Let us write action class for uploading. The action class will have 3 variables and 3 setter methods. Here the fileUpload interceptor will play major role to insert the uploaded file and related data into Action class using setter injection. The setter methods will have the format

setX(File file)
setXContentType(String contentType)
setXFileName(String fileName)

where X is the form field name to upload the file.

In our example (fileUpload.jsp), file1 is the name of the file tag and the action code with 3 variable are given below.

package javaonline.sample.struts2.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import com.opensymphony.xwork2.ActionSupport;

public class FileUpload extends ActionSupport  {

	private File file1;
        private String file1ContentType;
        private String file1FileName;

	public File getFile1() {
		return file1;
	}
	public void setFile1(File file1) {
		this.file1 = file1;
	}
	public String getFile1ContentType() {
		return file1ContentType;
	}
	public void setFile1ContentType(String file1ContentType) {
		this.file1ContentType = file1ContentType;
	}
	public String getFile1FileName() {
		return file1FileName;
	}
	public void setFile1FileName(String file1FileName) {
		this.file1FileName = file1FileName;
	}

	      public String execute() {

	    //...............   copy the code given in Step 7 and paste here.
		    return SUCCESS;
	      }

	      public String display() {
	  		return INPUT;
	  	}
	 } 

Step 3 : Now let us map the form with the action class using the struts.xml. The complete struts.xml file is given below.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

 <constant name="struts.devMode" value="true" />
 <constant name="struts.custom.i18n.resources" value="global"/>
 <constant name="struts.multipart.saveDir" value="c:/temp" />

 <package name="default" namespace="/" extends="struts-default">

<action name="loadFileUpload"
	    class="javaonline.sample.struts2.action.FileUpload" method="display">
	    <result name="input">fileUpload.jsp</result>
</action>

<action name="processFileUpload" class="javaonline.sample.struts2.action.FileUpload">
    <interceptor-ref name="basicStack"/>
    <interceptor-ref name="fileUpload">
            <param name="maximumSize">70000</param>
    </interceptor-ref>
    <interceptor-ref name="fileUpload">
        <param name="allowedTypes">image/jpeg,image/gif,image/jpg,image/png</param>
    </interceptor-ref>     

    <interceptor-ref name="params">
       <param name="excludeParams">dojo\..*,^struts\..*</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="input">fileUpload.jsp</result>
    <result name="success">Acknowledgement.jsp</result>
</action>
 </package>
</struts>

The parameters maximumSize, allowedTypes are passed to fileUpload interceptor for validation. If the size of the file (eg. picture000.jpg) is greater than 500000 bits, then the below error is thrown
The file is to large to be uploaded: file1 “picture000.jpg” “upload_eaa87531_1c59_472f_8067_e42b3e760d04_00000000.tmp” 60022

If you upload the file type other than the type jpeg,gif,jpg and png, the below error is thrown
Content-Type not allowed: file1 “PROD_SERVER.rsp” “upload_eaa87531_1c59_472f_8067_e42b3e760d04_00000001.tmp” text/plain

Step 4 (Optional): Override the default error message. You can override the above errors using the global.propeties as given below and adding the line “<constant name=”struts.custom.i18n.resources” value=”global”/>” to struts.xml file.

global.properties

<p style="text-align: justify;">struts.messages.error.uploading=An Error is occurred
struts.messages.error.file.too.large=File size is too large........
struts.messages.error.content.type.not.allowed=file type not allowed
struts.messages.error.file.extension.not.allowed=File extension is not allowed</p>

Step 5: Create an acknowledgement jsp as given below to get the successful message, when the file upload is completed successfully.

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload Summary</title>
</head>
<body>
<h3>File Uploaded successfully and the  details are</h3>

   File Name : <s:property value="file1FileName"/> <br/>

   Content Type : <s:property value="file1ContentType"/> <br/>

   File : <s:property value="file1"/> 

 </body>
</html>

The acknowledgement page displays the filename, file content type (mime type) , and temporary file(.tmp) name with path.

Step 6: Copy the .tmp file to your own path. By default, when you upload the file, the contents of the file is uploaded as upload___.tmp file. To copy the .tmp file to any path in the server with the original file name, use the below code in the execute method.

try{
       String filePath = "c:/temp"; // Server Path where the file to be uploaded.
     File file2 = new File(filePath, file1FileName);//file1FileName is the filename of the file you selected to upload
      FileUtils.copyFile(file1, file2); // copies the tmp file content to this file 

    }catch (Exception e)
      {
        return INPUT;
       }

Note : Keep the struts.xml and global.properties under /src folder.

Run the project by calling the URL http://localhost:8080/Struts2Sample/loadFileUpload

file upload 1
When you upload the file having size greater than the size mentioned in the struts.xml file using the param maximumSize, the below error is displayed.

file upload 2

When the file is uploaded successfully, the below acknowledgement screen appears.

Acknowledgement page

Reference : Apache Struts 2 FIle Upload 

You may also like

Leave a Reply