Monday, January 10, 2011

File upload in Struts Example

Step 1. Create a form bean

public class FileUploadForm extends ActionForm {
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
}

Step 2.
In the struts-config.xml file add: 
<form-bean name="FileUploadForm" type="com.techfaq.form.FileUploadForm"/>

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

<action path="/FileUploadAndSave" type="com.techfaq.action.FileUploadAndSaveAction" name="FileUploadForm"
scope="request" validate="true" input="/pages/fileupload.jsp">
<forward name="success" path="/jsp/success.jsp"/>
</action>

Step 4.
In the JSP
<html:form action="/FileUploadAndSave" method="post" enctype="multipart/form-data">
File Name :
<html:file property="file"/>
<html:submit>Upload File</html:submit>
</html:form>

Step 5.
In the Action class write the code

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
FileUploadForm myForm = (FileUploadForm)form;
// Process the FormFile
FormFile file = myForm.getFile();
String contentType = file.getContentType();
//Get the file name
String fileName = file.getFileName();
int fileSize = file.getFileSize();
byte[] fileData = file.getFileData();

//Get the servers upload directory real path name
String filePath = getServlet().getServletContext().getRealPath("/") +"uploadfile";
/* Save file on the server */
if(!fileName.equals("")) {
System.out.println("Server path:" +filePath);
//Create file
File fileToCreate = new File(file, fileName);
//If file does not exists create file
if(!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(file.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
return mapping.findForward("success");
}

File will be uploaded to "uploadfile" directory og your server.    

No comments:

Post a Comment