Home Struts Struts2 Struts 2 File Upload

Related Tutorials


 
 

Share on Google+Share on Google+

Struts 2 File Upload

Advertisement
In this section you will learn how to write program in Struts 2 to upload the file on the server. In this example we are also providing the code to save the uploaded file in any directory on the server machine.

Struts 2 File Upload

     

In this section you will learn how to write program in Struts 2 to upload the file on the server. In this example we are also providing the code to save the uploaded file in any directory on the server machine.

The Struts 2 FileUpload component can be used to upload the multipart file in your Struts 2 application. In this section you will learn about the code to upload file on the server.

How File Upload Works in Struts 2?

Struts 2 utilizes the service of  File Upload Interceptor to add the support for uploading files in the Struts applications. 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 (assuming the uploaded file name is MyFile). 

  • [MyFile] : File - the actual File
  • [MyFile]ContentType : String - the content type of the file
  • [File Name]FileName : String - the actual name of the file uploaded (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, setMyfile(File file), setMyFileContentType(String contentType), getMyFile(), etc..

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

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.
  • allowedTypes This parameter is also optional. It allows you to specify the allowed content type.

Writing Example code to upload file

Now we will write the code to upload the file on server.

Action Class

In the action class we will define four properties to facilitate the file upload.

private File upload; // The actual file

private String uploadContentType;// The content type of the file

private String uploadFileName;// The uploaded file name and path

private String fileCaption;// The caption of the file entered by user.

Here is the full code of action class StrutsFileUpload.java

package net.roseindia;
import java.util.Date;
import java.io.File;
import com.opensymphony.xwork2.ActionSupport;
public class StrutsFileUpload extends ActionSupport {
  
  private File upload;//The actual file
  private String uploadContentType; //The content type of the file
  private String uploadFileName; //The uploaded file name
  private String fileCaption;//The caption of the file entered by user
  public String execute() throws Exception {

  return SUCCESS;

  }
  public String getFileCaption() {
  return fileCaption;
  }
  public void setFileCaption(String fileCaption) {
  this.fileCaption = fileCaption;
  }
  public File getUpload() {
  return upload;
  }
  public void setUpload(File upload) {
  this.upload = upload;
  }
  public String getUploadContentType() {
  return uploadContentType;
  }
  public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
  }
  public String getUploadFileName() {
  return uploadFileName;
  }
  public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
  }

  
}

Here we have not shown the code to save the uploaded file. But it can be done easily using the following code in execute(..) method of action class. Here is code snippet.

//Following code can be used to save the uploaded file

try {

String fullFileName = "c:/upload/myfile.txt";

File theFile = new File(fullFileName);

FileUtils.copyFile(upload, theFile);

} catch (Exception e) {

addActionError(e.getMessage());

return INPUT;

}

Writing JSP page

Here is the code of jsp file (upload.jsp) that displays the file upload form to the user.

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>File Upload Example</title>
<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>

</head>

<body>

<s:actionerror />
<s:fielderror />
<s:form action="doUpload" method="POST" enctype="multipart/form-data">
<tr>
<td colspan="2"><h1>File Upload Example</h1></td>
</tr>

<s:file name="upload" label="File"/>
<s:textfield name="caption" label="Caption"/>
<s:submit />
</s:form>
</body>
</html>

In the above code the form encrypt type is "multipart/form-data" and <s:file ../> tag renders the html file tag.

File upload success page

Here is the code of file upload(upload-success.jsp) success page.

<%@ page 
language="java" 
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Showcase</title>
<link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/>
</head>

<body>
<table class="wwFormTable">
<tr>

<td colspan="2"><h1>File Upload Example</h1></td>
</tr>

<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">Content Type:</label></td>
<td><s:property value="uploadContentType" /></td>
</tr>

<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File Name:</label></td>
<td ><s:property value="uploadFileName" /></td>
</tr>


<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File:</label></td>
<td><s:property value="upload" /></td>
</tr>

<tr>
<td class="tdLabel"><label for="doUpload_upload" class="label">File Caption:</label></td>
<td><s:property value="caption" /></td>
</tr>


</table>

</body>
</html>

Adding mapping in struts.xml file

Add the following mapping in the struts.xml file.

<!-- File Upload -->

<action name="showUpload">
<result>/pages/upload.jsp</result>
</action>

<action name="doUpload" class="net.roseindia.StrutsFileUpload">
<result name="input">/pages/upload.jsp</result>
<result>/pages/upload-success.jsp</result>
</action>

<!-- End File Upload -->

The "showUpload" action displays the upload form and "doUpload" action actually uploads the file.

Running the example

To test the application compile code and then run the tomcat. Type http://localhost:8080/struts2tutorial/roseindia/showUpload.action in your browser. You browser should show the following form:

 

Now browse the file, enter caption and then click on the "Submit" button. Application will upload your file and then following success screen will be displayed.

 

There is one important point to be noted about File Upload Interceptor. The File Upload Interceptor actually deletes the the upload, once the action is executed. Here is the screen shot of tomcat that shows the file delete message:

INFO: Removing file upload C:\apache-tomcat-6.0.10Struts2\apache-tomcat-6.0.10\work\Catalina\
localhost\struts2tutorial\upload__13f532f7_1132e1d4754__8000_00000000.tmp

In this section you learnt the concept of file upload in struts 2.

     


 
Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: March 14, 2008

Related Tutorials

Discuss: Struts 2 File Upload   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:5
Andrea
June 7, 2011
struts 2.2.3 multiple file upload issues

I'm using file upload interceptor to upload multiple files via jsp page. I got the file uploaded in the temp folder but in my action class all the properties (filenames, content-type, ecc) are empty! below my code: private List<File> fileUpload = new ArrayList<File>(); private List<String> fileUploadContentType = new ArrayList<String>(); private List<String> fileUploadFileName = new ArrayList<String>(); public List<File> getFileUpload() { return fileUpload; } public void setFileUpload(List<File> fileUpload) { this.fileUpload = fileUpload; } public List<String> getFileUploadContentType() { return fileUploadContentType; } public void setFileUploadContentType(List<String> fileUploadContentType) { this.fileUploadContentType = fileUploadContentType; } public List<String> getFileUploadFileName() { return fileUploadFileName; } public void setFileUploadFileName(List<String> fileUploadFileName) { this.fileUploadFileName = fileUploadFileName; } public String upload() throws Exception{ for (File file: fileUpload) { System.out.println("File :" + file); } for (String fileName: fileUploadFileName) { System.out.println("Filename : " + fileName); } for (String fileContentType: fileUploadContentType) { System.out.println("File type : " + fileContentType); } return SUCCESS; } public String display() { return NONE; } I need to rename all file uploaded but I can't! Can anyone help me ??? I'm using tomcat 7.0.14 and jdk 1.6.0.25 Thanks in advance. Best regards
fancy
March 16, 2012
uploading in struts2

i'm trying to upload a file in struts2 but i'm getting an error : file not found exception.
White_King
May 26, 2012
Error

How can i send an error message or validation error message if the file is corrupted or is not the template expected?
iksan
June 18, 2012
nice tutorial

tq for this tutorial
vaibhav
September 21, 2012
upload image

i want upload image n struts2.0 when i click on the browser button then image show on imagebox. please help me.....
DMCA.com