Uploading Files with Actions in struts

Uploading Files with Actions in struts

Previous Home Next

 

In this chapter, 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. 

 

Directory Structure of FileUploadExample in Struts 1.3 Using MyEclipse IDE




index.jsp

<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<html>
<head>
<title><bean:message key="welcome.title"/></title>
</head>
<body>
<html:form method="POST" action="/upload" enctype="multipart/form-data" >
<h3><bean:message key="welcome.heading"/></h3>
<html:errors />
<table border="0" cellspacing="6" cellpadding="5">
<tr>
<td><bean:message key="welocome.first" /></td>
<td><html:text property="name" size="30" /></td></tr>
<tr><td><bean:message key="welocome.second" /></td>
<td><html:file property="document" size="30" /></td></tr>
<tr><td align="center"><html:submit property="submit" value=" Upload File " /></td>
<td><html:reset property="reset" value=" Reset " /></td></tr>
</table>
</html:form>
</body>
</html>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 
<web-app>
  <display-name>Maven Struts Examples</display-name> 
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet> 
  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping> 
</web-app>

struts-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">
<struts-config>
    <form-beans>
        <form-bean name="UploadForm" type="org.r4r.struts.UploadForm" />  
    </form-beans>
    <global-exceptions>
    </global-exceptions>
    <global-forwards>
    </global-forwards>
    <action-mappings>
        <action path="/uplo" type="org.apache.struts.actions.ForwardAction" parameter="/index.jsp"></action>
        <action input="/index.jsp" name="UploadForm" path="/upload" scope="request" type="org.r4r.struts.UploadAction">
            <forward name="success" path="/display.jsp"/>
        </action>
    </action-mappings>
    <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
    <message-resources parameter="org.r4r.struts.ApplicationResources"/>

    <!-- ========================= Tiles plugin ===============================-->

    <plug-in className="org.apache.struts.tiles.TilesPlugin" >
        <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
        <set-property property="moduleAware" value="true" />
    </plug-in>

    <!-- ========================= Validator plugin ================================= -->
    <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
        <set-property
            property="pathnames"
            value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
    </plug-in>
</struts-config>

UploadForm.java

package org.r4r.struts;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;


@SuppressWarnings("serial")
public class UploadForm extends org.apache.struts.action.ActionForm {

    private String name = null;
    private FormFile document = null;

    public String getName() {
        return name;
    }

    public void setName(String string) {
        name = string;
    }

    public FormFile getDocument() {
        return document;
    }

    public void setDocument(FormFile document) {
        this.document = document;
    }

    public UploadForm() {
        super();
    }

    @Override
    public void reset(ActionMapping mapping, HttpServletRequest request) {
        name = null;
        document = null;
    }

    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (name == null || name.length() < 1) {
            errors.add("name", new ActionMessage("error.name.required"));
        }
        if (document.getFileSize() == 0) {
            errors.add("Zerosize", new ActionMessage("error.Zerosize.required"));
        }
        return errors;
    }
}

UploadAction.java

package org.r4r.struts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class UploadAction extends org.apache.struts.action.Action {
    private static final String SUCCESS = "success";
    private FileOutputStream outputStream = null;    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        UploadForm uploadForm = (UploadForm) form;
        FormFile formFile = null;
        try {
            formFile = uploadForm.getDocument();
            String path = getServlet().getServletContext().getRealPath("") + "/" + formFile.getFileName();
            outputStream = new FileOutputStream(new File(path));
            outputStream.write(formFile.getFileData());            
        } catch (Exception e) {
            throw new IOException(e.fillInStackTrace());
            } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            uploadForm.setDocument(formFile);
            request.setAttribute("SizeofFile", formFile.getFileSize());
        }
        return mapping.findForward(SUCCESS);
    }
}

ApplicationResources.properties

# -- welcome --
welcome.title=r4r.co.in
welcome.heading=<font face="Arial" color="green">Struts application for Upload document into browser!</font>
welcome.message=It's easy to create Struts applications with NetBeans.
welocome.first=<font face="Arial" color="#008000"> Enter the name of Document: </font>
welocome.second=<font face="Arial" color="#008000"> Choose the Upload Document: </font>
welcome.dispaly=<font face="Arial" color="green"> Document successfully Upload into your Browser!</font>
#-- Error --
error.name.required= error.Name of Document.required
error.Zerosize.required= error.Upload document.null

display.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<title>Dispaly Page</title>
</head>
<body>
<h3><bean:message key="welcome.dispaly"/></h3>
Name of File: <b> <bean:write name="UploadForm" property="name" /></b><br/><br/>
Name of Upload File:<b> <bean:write name="UploadForm" property="document" /></b><br/><br/>
Size of Upload File:<b> <%= request.getAttribute("SizeofFile")%> bytes </b><br/><br/>
<img src="<bean:write name="UploadForm" property="document" />"
width="200" height="100" alt="<bean:write name="UploadForm" property="name" />"/><BR/><Br/>
<strong>Only Image file display, but you can esily download any file link given below </strong><br/>
<a href="<bean:write name="UploadForm" property="document" />"> Click here to download that file</a>
</body>
</html>

Output




Previous Home Next