Uploading Files with Actions in struts

In this post, We will discuss how to allow the user to upload a file using Struts framework. to enable the user to upload a file,We need to set the encoding type of html:form tag to "multipart/form-data" and specify the HTTP method as "post".The property file in the FileUploadForm is of type org.apache.struts.upload.FormFile. 
Create upload.jsp :-

<html>
   <head>
   <title> Upload File</title>  
 </head>
   <body>
   <html:errors />
     <html:form action="/FileUploadUpdate" method="post" enctype="multipart/form-data">
     Select File : <html:file property="userfile" />
<br/>
     <html:submit />
     </html:form>
   </body>
</html>

Now Create FileUploadAction class :-

package WiseDeveloper.co.in;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.upload.FormFile;
public class FileUploadAction extends org.apache.struts.action.Action { 
    private final static String Key = "success";   
public ActionForward execute(ActionMapping mapping, ActionForm form,  HttpServletRequest request, HttpServletResponse response)   throws Exception {   
    ImageUploadForm uploadForm = (ImageUploadForm) form;       
FileOutputStream outputStream = null;       
FormFile formFile = null; 
      try {            formFile = uploadForm.getFile();     
      String path = getServlet().getServletContext().getRealPath("")+"/"+ formFile.getFileName();   
        outputStream = new FileOutputStream(new File(path));   
        outputStream.write(formFile.getFileData());     
  }
finally {            if (outputStream != null) {     
          outputStream.close();         
  }       
}       
uploadForm.setMessage("The File is uploaded successfully.");       
return mapping.findForward(Key);   
}
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More