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: , , , , , , , , ,