Frameworks| Hibernate| Struts| JSF| JavaFX| Ajax| Spring| DOJO| JDO| iBatis| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Struts File Upload Example 
 

In this tutorial you will learn how to use Struts to write program to upload files.

 

Struts File Upload Example

                         

In this tutorial you will learn how to use Struts to write program to upload files. The interface org.apache.struts.upload.FormFile is the heart of the struts file upload application. This interface represents a file that has been uploaded by a client. It is the only interface or class in upload package which is typically referenced directly by a Struts application.

Creating Form Bean

Our form bean class contains only one property theFile,  which is of type org.apache.struts.upload.FormFile.

 

Here is the code of FormBean (StrutsUploadForm.java):

package roseindia.net;


import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;



/**
@author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

/**
 * Form bean for Struts File Upload.
 *
*/
public class StrutsUploadForm extends ActionForm
{
  private FormFile theFile;

  /**
   @return Returns the theFile.
   */
  public FormFile getTheFile() {
    return theFile;
  }
  /**
   @param theFile The FormFile to set.
   */
  public void setTheFile(FormFile theFile) {
    this.theFile = theFile;
  }
}

Creating Action Class

Our action class simply calls the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile is used to get the uploaded file and its information. Here is the code of our action class(StrutsUploadAction.java):

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
/**
@author Deepak Kumar
* @Web http://www.roseindia.net
* @Email roseindia_net@yahoo.com
*/

/**
 * Struts File Upload Action Form.
 *
*/
public class StrutsUploadAction extends Action
{
  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse responsethrows Exception{
    StrutsUploadForm myForm = (StrutsUploadForm)form;

        // Process the FormFile
        FormFile myFile = myForm.getTheFile();
        String contentType = myFile.getContentType();
        String fileName    = myFile.getFileName();
        int fileSize       = myFile.getFileSize();
        byte[] fileData    = myFile.getFileData();
    System.out.println("contentType: " + contentType);
    System.out.println("File Name: " + fileName);
    System.out.println("File Size: " + fileSize);
    
      return mapping.findForward("success");
  }
}

Defining form Bean in struts-config.xml file

Add the following entry in the struts-config.xml file for defining the form bean:

<form-bean
    name="FileUpload"
    type="roseindia.net.StrutsUploadForm"/>

Defining Action Mapping

Add the following action mapping entry in the struts-config.xml file:

<action
     path="/FileUpload"
     type="roseindia.net.StrutsUploadAction"
     name="FileUpload"
     scope="request"
     validate="true"
     input="/pages/FileUpload.jsp">
     <forward name="success" path="/pages/uploadsuccess.jsp"/>
</action>

Developing jsp page

Code of the jsp (FileUpload.jsp) file to upload is as follows:

<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>

<html:html locale="true">
<head>
<title>Struts File Upload Example</title>
<html:base/>
</head>
<body bgcolor="white">
<html:form action="/FileUpload" method="post" enctype="multipart/form-data">
<table>
<tr>
<td align="center" colspan="2">
<font size="4">Please Enter the Following Details</font>
</tr>

<tr>
<td align="left" colspan="2">
<font color="red"><html:errors/></font>
</tr>



<tr>
<td align="right">
File Name
</td>
<td align="left">
<html:file property="theFile"/> 
</td>
</tr>


<tr>
<td align="center" colspan="2">
<html:submit>Upload File</html:submit>
</td>
</tr>
</table>


</html:form>
</body>
</html:html>

Note that we are setting the encrypt property of the form to enctype="multipart/form-data".

code for the success page (uploadsuccess.jsp) is:

<html>

<head>
<title>Success</title>
</head>

<body>

<p align="center"><font size="5" color="#000080">File Successfully Received</font></p>

</body>

</html>

Add the following line in the index.jsp to call the form.

<li>
<html:link page="/pages/FileUpload.jsp">Struts File Upload</html:link>
<br>
Example shows you how to Upload File with Struts.
</li>

Building Example and Testing

To build and deploy the application go to Struts\strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the FileUpload.jsp page. Your browser should display the file upload form:
  

                         

» View all related tutorials
Related Tags: c exception time io scope multiple type request cookie default ip page value tag name attribute this oo row define

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

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

hi getting following error, plz help....

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

javax.servlet.ServletException: org.apache.struts.util.RequestUtils.getModuleConfig(Ljavax/servlet/jsp/PageContext;)Lorg/apache/struts/config/ModuleConfig;
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.index_jsp._jspService(org.apache.jsp.index_jsp:91)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)


root cause

java.lang.NoSuchMethodError: org.apache.struts.util.RequestUtils.getModuleConfig(Ljavax/servlet/jsp/PageContext;)Lorg/apache/struts/config/ModuleConfig;
org.apache.struts.taglib.html.FormTag.lookup(FormTag.java:795)
org.apache.struts.taglib.html.FormTag.doStartTag(FormTag.java:506)
org.apache.jsp.index_jsp._jspx_meth_html_form_0(org.apache.jsp.index_jsp:107)
org.apache.jsp.index_jsp._jspService(org.apache.jsp.index_jsp:81)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)

Posted by shaily on Friday, 07.10.09 @ 11:59am | #89220

since so many days i have been looking for this logic. now i got that. thank you very much.

Posted by S.Praveen Reddy on Monday, 12.1.08 @ 22:54pm | #82260

Try to upload any file (MSWord) using struts FormFile while the file is opened. The content type returned is the struts default content type CSV and not the correct file type.

Please help to overcome the issue?

Posted by Saumya on Thursday, 10.2.08 @ 14:47pm | #80840

htp.formopen(url_prefix||'home.home_pow.process', 'post', cenctype => 'multipart/form-data', cattributes =>'name="upload"');

htp.tablerowopen;
htp.tabledata(' ');
htp.tablerowclose;

htp.tablerowopen;
htp.tabledata('Please select the file to be uploaded:', cattributes=>'align="right"');
htp.tabledata(htf.formfile('uploadFile','application/msword')||' <img src="' ||server_prefix|| 'images/ico-word-18x18.jpg" border="0">');
htp.tablerowclose;

Posted by Nona on Thursday, 09.18.08 @ 20:58pm | #80350

hi, first thanks for the example! i'm using a form with an upload field and a regular input field. if the validation for the text field fails, the form page is displayed with the validation message as expected. only the uploaded data is no longer in the upload field. does anyone know a solution to this problem?

Posted by tom on Friday, 08.1.08 @ 16:42pm | #70314

Hi!
This is my question, i have developed an web application in struts where i have facing some unusual uploading time, size of file were more than 5MB, actually time taking in web server to upload an file is not an problem,i need an success page immediatly after clicking "upload file " button. but i can't move to succes page before completing the upload process, do anybody have idea of showing the success page immediatly after submission, uploading action will be executed internally but not shown in front

Posted by Senthil kumar on Monday, 07.7.08 @ 12:46pm | #66109

Hi All
please solve my problem
when i upload any file or image after that i refresh the page or any error coming then image path that i select it going blank
please tell me how i solve that problem

Posted by Vipan on Monday, 06.2.08 @ 11:21am | #61790

I need write a servlet to not render html to browser, but instead to generate a file. Kind like to save a temp copy of browser view.

Does anyone have done something like this? I'd like to know how to do it.

Thanks,
Robert

Posted by Robert on Friday, 05.30.08 @ 00:08am | #61372

hi,

i want code pagenation code in jsp.

Posted by Nageswara Rao on Wednesday, 04.30.08 @ 11:49am | #58192

I have a question in the above example,it doesn't mention how the browser works?
what i want to do in my app. is click on a "browse" button so it opens a browser so that i can browse my computer and select a file (i want to get the filename along with the path) how can i do that ? is there an example or an already-made tutorial ?
p.s.:i'm working on windows xp

thanks

Posted by omar on Sunday, 03.23.08 @ 17:53pm | #53941

Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

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.