Saturday, September 11, 2010

File uploading and downloading in struts

Here i have written a tutorial for downloading and uploading the file to and from server to any directory on server.
This contstruts.
1)ActionForms
2)Action Classes
3)struts-config.xml
4)jsp


//UploadForm.java//


package mypack;

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

/**
 *
 * @author ANUJ ANEJA
 */
public class UploadForm extends ActionForm {

    private FormFile theFile;

    public UploadForm() {
        System.out.println("uploadForm constructor");
    }
    public FormFile getTheFile()
    {
        return this.theFile;
    }
    public void setTheFile(FormFile theFile)
    {
        System.out.println("setter");
        this.theFile=theFile;
    }


    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        return super.validate(mapping, request);
    }
   
}

//downloadForm.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mypack;

import org.apache.struts.action.ActionForm;

/**
 *
 * @author ANUJ ANEJAe
 */
public class DownloadForm extends ActionForm{

    private String fileName;

    public DownloadForm() {
        System.out.println("DownloadForm constructor");
    }

    public String getFileName()
    {
        return this.fileName;
    }
    public void setFileName(String fileName)
    {
        System.out.println("setter in download called");
        this.fileName=fileName;
    }
}
Action Classes.

UploadAction.java
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mypack;

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

/**
 *
 * @author ANUJ ANEJA
 */
public class UploadAction extends Action{


    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

        String forward="failure";
        try{
        UploadForm myform=(UploadForm)form;
        System.out.println("Pass>>>>>>>>>"+myform);
        FormFile myfile=myform.getTheFile();
         System.out.println("Pass1111>>>>>>>>>"+myfile);
        String contentType=myfile.getContentType();
        byte b[]=myfile.getFileData();
        int size=myfile.getFileSize();
        String fileName=myfile.getFileName();
        System.out.println("file details are:");
        System.out.println("Name-"+fileName+"\nType of content-"+contentType+"\nSize-"+size);
        String filePath=getServlet().getServletContext().getRealPath("/")+"upload";
        filePath="c:\\upload";
        if(!fileName.equals(""))
        {
            File file=new File(filePath,fileName);
            if(!file.exists())
            {
                FileOutputStream fout=new FileOutputStream(file);
                fout.write(b);
                fout.flush();
                fout.close();
            }
            request.setAttribute("fileName",fileName);
        }

        forward="success";
        }catch(Exception e)
        {
            System.out.println("Exception in uploadAction"+e);
            //e.printStackTrace();
        }
        return mapping.findForward(forward);
    }


}

struts-config.xml
<form-beans>
 <form-bean name="UploadForm" type="mypack.UploadForm"/>
    <form-bean name="DownloadForm" type="mypack.DownloadForm"/>
</form-beans>
<action path="/uploader" type="org.apache.struts.actions.ForwardAction" parameter="/uploadFile.jsp"/>
        <action path="/upload" type="mypack.UploadAction" name="UploadForm" validate="true"  input="/uploadFile.jsp" scope="request">
            <forward name="success" path="/download.jsp" />
            <forward name="failure" path="/failure.jsp" />
        </action>
        <action path="/download" type="mypack.DownloadAction" input="/download.jsp" name="DownloadForm" scope="request" validate="true">
            <forward name="success" path="/success.jsp" />
        </action>


JSPs

uploadFile.jsp

<%--
    Document   : uploadFile
    Created on : Sep 10, 2010, 7:53:42 PM
    Author     : ANUJ ANEJA
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="bean" uri="/WEB-INF/struts-bean.tld" %>
<%@taglib prefix="html" uri="/WEB-INF/struts-html.tld" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <html:form action="/upload.do" method="post" enctype="multipart/form-data">
            Select file to upload <html:file property="theFile"/><br>
            <html:submit>
                <bean:message key="message.upload" />
            </html:submit>
        </html:form>
    </body>
</html>

download.jsp

<%--
    Document   : download
    Created on : Sep 10, 2010, 11:55:32 PM
    Author     : ANUJ ANEJA
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="html" uri="/WEB-INF/struts-html.tld" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
            String fileName = (String) request.getAttribute("fileName");
            System.out.println("fname is::::" + fileName);
        %>

        <a href="upload/<%=fileName%>" >click to download</a>
        <br>
        <html:form action="/download.do">
        <html:hidden property="fileName"  value="<%=fileName%>"/>
        <html:submit >Another mirror</html:submit>
        </html:form>
    </body>
</html>

No comments:

Post a Comment