Home Struts Struts File Upload and Save
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Struts File Upload and Save

Advertisement
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" >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. .

Advertisement

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: May 16, 2007

Related Tutorials

Ask Questions?    Discuss: Struts File Upload and Save   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
manishsuriya.pune@gmail.com
April 10, 2011
uplaod using apache common uplaod

this is nice tutorila but can u please post an example using apache common uplaod. Thanks
roopa
May 26, 2011
struts

please briefly describe how to run a struts2 based application.i dnt have idea about struts version 2,thank u
Maroof Ahmad
September 8, 2011
Get Code From Side

Hi, How Can i get File Upload This Code. Please Send me detail Your Sincerely Maroof
stephen
October 10, 2011
getting error while uploading a image

error detail: argument type mismatch - had objects of type "java.lang.String" but expected signature "org.apache.struts.upload.FormFile"
pruthvi
January 25, 2012
uploading files doubt

if i clean the apache tomcat server in eclipse the uploaded files will be deleted , but i dont want that files to be deleted... give me solution soon please...
Zenul
March 22, 2012
AEcJUZUpQaasoysbHip

Wow, that's a really cveler way of thinking about it!
Lalitha
April 3, 2012
uploading a file to sql server database

In the above article we are storing the file on a server.. but if we want to store the file into a database which data type we have to use in the table to store the file..? and what code to be written in action class to store the file in database.. Please if anyone knows help me in doing this.. Thanks in advance Lalitha
MANUEL
October 24, 2012
Excellent

Excellent example to learn about struts and how to handle file backup. Keep doing the good work!
DMCA.com