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

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
 
Struts File Upload and Save 
 

In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file .

 

Struts File Upload and Save

                         

We are receiving lots of comments regarding  "Struts file upload example". It does not contain any code illustrating how to  save the file on the server . Now, the current example will  provide you with the code to upload the file ,in the upload directory of server. 

In this tutorial you will learn how to use Struts program to upload on the Server and display a link to the user to download the uploaded file . The interface org.apache.struts.upload.FormFile has a prime role in  uploading a  file in a Struts 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  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 (StrutsUploadAndSaveForm.java):

package roseindia.net;


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



/**
@author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net
*/

/**
 * Form bean for Struts File Upload.
 *
*/
public class StrutsUploadAndSaveForm 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

In our previous article entitled "Struts File Upload Example", we just had  action class simply calling the getTheFile() function on the FormBean object to retrieve the reference of the uploaded file. Then the reference of the FormFile was used to get the uploaded file and its information. Now  further we retrieve the Servers upload directory's real path using  ServletContext's  getRealPath() and saving the file.

Code of StrutsUploadAndSaveAction.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;
import java.io.*;

/**
@author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net
*/

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

        // Process the FormFile
        FormFile myFile = myForm.getTheFile();
        String contentType = myFile.getContentType();
    //Get the file name
        String fileName    = myFile.getFileName();
        //int fileSize       = myFile.getFileSize();
        byte[] fileData    = myFile.getFileData();
    //Get the servers upload directory real path name
    String filePath = getServlet().getServletContext().getRealPath("/"+"upload";
    /* Save file on the server */
    if(!fileName.equals("")){  
        System.out.println("Server path:" +filePath);
        //Create file
        File fileToCreate = new File(filePath, fileName);
        //If file does not exists create file                      
        if(!fileToCreate.exists()){
          FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
          fileOutStream.write(myFile.getFileData());
          fileOutStream.flush();
          fileOutStream.close();
        }  


    }
    //Set file name to the request object
    request.setAttribute("fileName",fileName);
      
        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="FileUploadAndSave"
type="roseindia.net.StrutsUploadAndSaveForm"/>

 Defining Action Mapping

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

<action
path="/FileUploadAndSave"
type="roseindia.net.StrutsUploadAndSaveAction"
name="FileUploadAndSave"
scope="request"
validate="true"
input="/pages/FileUploadAndSave.jsp">
<forward name="success" path="/pages/downloaduploadedfile.jsp"/>
</action>

Developing jsp pages

Code of the jsp (FileUploadAndSave.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 and Save Example</title>
<html:base/>
</head>
<body bgcolor="white">
<html:form action="/FileUploadAndSave" method="post" enctype="multipart/form-data">
<table>
<tr>
<td align="center" colspan="2">
<font size="4">File Upload on Server</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>

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

<html>

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

<body>
<%
String fileName=(String)request.getAttribute("fileName");
%>

<p align="center"><font size="5" color="#000080">File Successfully Received</font></p>
<p align="center"><a href="upload/<%=fileName%>">Click here to download</a></p>
</body>

</html>

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

<li>
<html:link page="/pages/FileUploadAndSave.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 Struts File Upload page. Your browser should display the file upload form:
  

Now , Browse the file needed to upload and click Upload File Button. Browser  will display that  file has successfully received on the server.

Click on the hyperlink to see the uploaded content. .

 

                         

» View all related tutorials
Related Tags: c web pdf file files orm form software control io custom drawing mail adobe free format ado quality read using

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

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

Nice example for uploading a file.

Posted by syam on Friday, 01.30.09 @ 04:08am | #84318

getServlet().getServletContext().getRealPath("/") +"upload";.........its returning c:\program files\..........webapps

Posted by ssssss on Monday, 10.6.08 @ 15:22pm | #80924

hi.......
i want to insert a file into a database and retrieve it using struts can any one help me

Posted by kishore on Tuesday, 09.30.08 @ 13:24pm | #80794

Hi i am getting the exception of file not found can any at above code
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
so please help me it this

Sandy

Posted by Sandy on Thursday, 05.29.08 @ 15:18pm | #61345

The code displaying 500 Error. Update to me solution of the problem.

--------------------------------------------------------------------------------

type Exception report

message

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

exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /pages/FileUploadAndSave.jsp at line 10

7: <html:base/>
8: </head>
9: <body bgcolor="white">
10: <html:form action="/FileUploadAndSave" method="post" enctype="multipart/form-data">
11: <table>
12: <tr>
13: <td align="center" colspan="2">


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:398)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:806)


note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.


--------------------------------------------------------------------------------

Posted by Giridhar on Thursday, 05.22.08 @ 19:16pm | #60673

How I catch File not found exception?

Posted by Wut on Monday, 04.21.08 @ 09:17am | #57371

iam getting an error like this


java.lang.IllegalArgumentException: argument type mismatch


wat happened plz help

Posted by Anil on Sunday, 03.9.08 @ 18:36pm | #52117

I want to view repost from database in JSP but this report shoud be view in PDF format.
so, i need source code the example.
please as soon as possible give a example with html and jsp on the broswer.
Shyam

Posted by Shyam on Friday, 02.8.08 @ 14:13pm | #47602

iam getting exception creating bean of class plz help me

Posted by srinivas on Wednesday, 12.26.07 @ 14:19pm | #43832

Fantastic Struts example. Could someone give me the equivilant on the Java Server Faces framework. I have built the version that basically upload the file but does not save the file to a folder on the server. Could I please see the working code on this process. From upload to saving the image file on a server folder. It would be very much appreciated.

Posted by Brian Brocksmith on Tuesday, 12.18.07 @ 21:10pm | #42854

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
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.