Monday, August 6, 2007

Upload files using struts framework


Recently i' ve an urgent need to know uploading/downloading file in struts,
i found this more than easy,
using org.apache.struts.upload.FormFile class for file uploading.


Here are the steps of uploading file - to the server - in a struts application:


1- create new web project with struts framework enabled.

2- open the struts-config.xml file, add a new form-bean,
pointing to a class used for validating
the upload_file form,
and for retrieving the uploaded file later in the action class:


<form-bean name="UploadForm"
type="upload.forms.UploadForm"/>


Notes:
name – id of the form to be used in action tags
type – the full class name, this class should
extend org.apache.struts.action.ActionForm,
to access the jsp form input data


3- inside <action-mappings> tag, add new action, pointing to your action class
that will process input data:


<action validate="true" input="/upload.jsp"
name="UploadForm" path="/upload" scope="request"
type="upload.actions.Upload">


<!-- forward mapping tags, see next step -->
<
/action>


Notes:
input - is the next page that will displayed
in case of validation error occurred

name - referencing the associated name of
from which input data will be processed

path - is the relative url to this action class,
used in href or form action html attributes

type - the full action class name, the class
should extend org.apache.struts.action.Action


4- add the forward element inside your action , to state the next page displayed
in case of successful uploading, or uploading failure:


<action validate="true" input="/upload.jsp"
name="UploadForm" path="/upload" scope="request"
type="upload.actions.Upload">

<forward name="success" path="/success.jsp"/>
<
forward name="failure" path="/failure.jsp"/>
<
/action>


Note:
name – used later in the action class,
passed to the ActionMapping object as a parameter


5- now you have to implement all the classes given in struts-config.xml,
create a new java class extending org.apache.struts.action.ActionForm,
this is the form bean class, it will have org.apache.struts.upload.FormFile object
with setter & getter method, refering to the <INPUT> tag in your jsp form,
this class also overrides the validate method of ActionForm:


public class UploadForm extends
org.apache.struts.action.ActionForm {


private FormFile file;

public FormFile getFile() {
return file;
}

public void setFile(FormFile file) {
this.file = file;
}

public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request)
{

ActionErrors errors = new ActionErrors();
if (getFile() == null
getFile().getFileName()==null
getFile().getFileName().length()==0)
{

errors.add("file",
new ActionMessage("error.file.required"));

}
return errors;
}
}


6- create the action class, extending org.apache.struts.action.Action,
override the execute method to save the uploaded file in server file system (as an example),
it's very easy to retrieve inputStream of the uploaded file using 
FormFile getInputStream() method:


public class Upload extends Action {

public ActionForward execute(
ActionMapping mapping, ActionForm form,

HttpServletRequest request,
HttpServletResponse response)


throws Exception
{


ActionForward forward=new ActionForward();
try{
UploadForm fileform=(UploadForm)form;
File attachsFolder=
new File("C:\\TemporaryAttachment");

boolean dirCreated=attachsFolder.mkdir();
if(dirCreated attachsFolder.exists())
{

// reserve empty file to fill with the uploaded file
FileOutputStream fout=
new
FileOutputStream(
attachsFolder.getCanonicalPath()+
File.separator+"fileUploaded.txt");

InputStream uploadStream=
fileform.getFile().getInputStream();

byte[]b=new byte
[uploadStream.available()];

uploadStream.read(b);
fout.write(b);
uploadStream.close();
fout.close();
forward=mapping.findForward("success");
}
else{
request.setAttribute("error",
"unable to locate temp"+
"attachments directory");

forward=mapping.findForward("failure");
}

}catch(Exception e)
{
e.printStackTrace();
request.setAttribute("error",
e.getLocalizedMessage());

forward=mapping.findForward("failure");
}
return forward;

}
}

/////////////// Finished :)

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

Downloading file is so simple too, & will be mentioned later in a new post.


No comments: