1600 PMP mock questions 1400 CAPM mock questions 800 SCJP 6 mock questions 600 OCAJP 7 mock questions 590 OCPJP 7 mock questions 556 SCWCD 5 mock questions 500 OCEJWCD 6 mock questions pdfDownload (java,struts, hibernet etc)

Struts Tutorials

Q. How to do File Upload in Struts ?

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 oploaded to "uploadfile" directory og your server.

Reviews and Comments


PMP, CAPM, PMI is a registered certification mark of the Project Management Institute, Inc

Copyright © www.techfaq360.com 2016


About US | Contact US | Privacy Policy | Terms and Conditions  | Website disclaimer  | Cancellation and Refund Policy  | Shipping & Delivery Policy