Techie Baba

Tuesday, November 06, 2007

File Upload using STRUTS

1. HTML code snippet for file upload:

<FORM name="uploadForm" ENCTYPE='multipart/form-data' method="POST" action="/Upload.do">
<LABEL FOR="theFile">File to be Uploaded:</LABEL>
<INPUT TYPE="file" NAME="myFile">
<INPUT TYPE="submit" NAME="uploadButton" value="Upload File">
</FORM>

You need to specify ENCTYPE attribute of the FORM as 'multipart/form-data' to submit the file as a part of POST request.

2. Create an ActionForm:
ActionForm has a property having same name as file input field in the HTML (<INPUT TYPE="file" NAME="myFile">)

public class UploadFileForm extends ActionForm {
private FormFile myFile;

public FormFile getMyFile() {
return myFile;
}

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


3. Changes in struts-config.xml

Form Bean:
<form-beans>
<form-bean name="uploadFileForm" type="com.shashank.UploadFileForm">
</form-bean>

Action Mapping:
<action-mappings>
<action path="/Upload" type="com.shashank.UploadAction" name="uploadFileForm">
<forward name="success" path="/jsp/Uploader.jsp" />
<forward name="failure" path="/jsp/error.jsp" />
</action>
<action-mappings>

4. Action Class:

public class UploadAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
UploadFileForm fileForm = (UploadFileForm)form;

FormFile myFile = fileForm.getMyFile();
if (myFile != null) {
String fileName = myFile.getFileName();
String filePath = "/upload"; //define the directory where you need to upload

/* Save file on the server */
if(!fileName.equals("")) {
File file = new File(filePath );
file.mkdirs();

File fileToCreate = new File(filePath, fileName);
if(!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
} // END : if(!fileToCreate.exists())
} // END : if(!fileName.equals(""))
} // END : if (myFile != null)
} catch (Exception e) {
e.printStackTrace();
}
} // END of execute()
}

This article has now moved to my new BLOG.

Labels: , , , , , , , , ,

1 Comments:

  • Hi, i am trying to use a similar approach to upload a file to a specific location.Its working fine but i noticed that the original file file that was uploaded cannot be deleted.It seems as if the File handle is not being released(Not sure about it though). Please do let me know in case you have ever come across similar issue and have solved it.

    Thanks

    By Blogger Vijeesh, at March 12, 2009 7:00 AM  

Post a Comment

<< Home