How to do File Upload in Struts

Here I am explaining how to do file upload in struts .

FileForm

package com.fileupload;
import org.apache.struts.upload.FormFile;
import org.apache.struts.action.ActionForm;

/**
*
* @author Prasanthi
*
*/
public class FileForm extends ActionForm{

private FormFile file1;

public FormFile getFile1() {
return file1;
}

public void setFile1(FormFile file1) {
this.file1 = file1;
}

}

FileAction

package com.fileupload;

import org.apache.struts.upload.FormFile;
import org.apache.struts.action.*;
import javax.servlet.http.*;

/**
*
* @author Prasanthi
*
*/
public class FileAction extends Action{
public ActionForward execute(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res)throws Exception
{
FileForm file2=(FileForm)form;
FormFile fil=file2.getFile1();
String fname=fil.getFileName();
String ctype=fil.getContentType();
int fsize=fil.getFileSize();
String size=Integer.toString(fsize);
byte [] data=fil.getFileData();

req.setAttribute("FileName",fname);
req.setAttribute("FileSize",size);
req.setAttribute("ContentType",ctype);
req.setAttribute("FileData",data);

return map.findForward("success");

}

}

struts-config.xml

<struts-config>

<form-beans>
<form-bean name="fileuploadbean" type="com.fileupload.FileForm" />
</form-beans>

<action-mappings>
<action path="/fileupload"
name="fileuploadbean"
type="com.fileupload.FileAction"
scope="request"
input="/FileUpload.jsp">
<forward name="success" path="/FileUploadSuccess.jsp"/>
</action>
</action-mappings>

</struts-config>

web.xml

<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>FileUpload.jsp</welcome-file>
</welcome-file-list>

<taglib>
<taglib-uri>/tags/struts-html</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
</web-app>

FileUpload.jsp

<%@ taglib uri="/tags/struts-html" prefix="html"%>
<html:html>

<body><br><br>
<center><h2><u>File Upload</h2></u>
<html:form action="/fileupload" method="post" enctype="multipart/form-data">

Enter File:<html:file property="file1" /><br><br>
<html:submit value="upload" />
</html:form>
</body>
</html:html>


FileUploadSuccess.jsp

<html>
<body>
<br><br>
<center>
<h2><u>Upload File Details</u></h2>

<b>
FileName:<%=(String)request.getAttribute("FileName")%><br>
FileSize:<%=request.getAttribute("FileSize")%><br>
ContentType:<%=(String)request.getAttribute("ContentType")%><br>

</html>

No comments: