Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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.

                         


 

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

14 comments so far (
post your own) View All Comments Latest 10 Comments:

Really useful

Posted by any on Thursday, 12.11.08 @ 03:26am | #82639

This is the problem Iam getting when Iam running your file upload example
Unable to load bean org.apache.struts2.dispatcher.multipart.MultiPartRequest (jakarta) - [unknown location]
How to solve it
Regards
Febin

Posted by febin on Monday, 04.28.08 @ 17:35pm | #58064

Hi,
Could anyone show me how to upload more than one file?

Many thanks!

Posted by kienjudo on Tuesday, 03.4.08 @ 09:00am | #51251

Hi friends.....
i tried uploading all type of files....
now i want to upload only pictures of jpeg format......
Can u suggest me a solution?

Posted by srinadh on Wednesday, 02.20.08 @ 12:09pm | #49186

If you want to upload files bigger than 2mb in your struts.properties file, you must set this attribute

struts.multipart.maxSize

This value defaults to 2mb, if you want your fileupload interceptor to to manage max file size you must set this value to be larger than the interceptor setting.

And if you don't know... here is how you set it from the interceptor

<interceptor-ref name="fileUpload">
<param name="maximumSize" >1024</param>
<param name="allowedTypes">image/png,image/gif,image/jpeg,image/jpg</param>
</interceptor-ref>

Just put those lines inside of your action definition in your struts.xml.


Posted by trevis on Tuesday, 02.19.08 @ 22:32pm | #49113

As was said below, you need to download commons-fileupload and commons-io and add them to your lib folder.

But for it to work you also need to have a struts.properties file and add this line to it:

struts.multipart.parser=org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest

Posted by trevis on Thursday, 02.14.08 @ 11:42am | #48232

i executed what ever givin in above example..
but no valuse diaplay

File Upload Example
Content Type:
File Name:
File:
File Caption:

















any problam in above code given in dis page

Posted by raju on Saturday, 01.26.08 @ 15:32pm | #46235

Hi, I have a page with 2 submit buttons: one to upload the file and one to view the file. The "view button" reload the page to update a table. My problem is that when I reload the page, the path of the selected file isn't visible anymore and I think is a little confuse to the user.

Can you give some me help with this?

Posted by Adriana on Wednesday, 01.2.08 @ 18:39pm | #44371

Hi,

I've done all the stuff necessary to save the file I uploaded but the one thing I can't figure out is how to save to a specific directory. Can someone please help?

Posted by Gau on Friday, 12.7.07 @ 09:09am | #41497

put struts.properties file in you WEB-INF/classes folder with the following entry:
struts.multipart.maxSize=1024000000

Posted by Juby Rajan on Monday, 09.10.07 @ 19:18pm | #26600

Join and Excel yourself with our Online instructor led training sessions
Training Courses
Tell A Friend
Your Friend Name

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.