Saturday, September 11, 2010

Multiple files uploading in Struts.

For implementing multiple file upload all u need to do is have and Arraylist to save file in it and render it to upload through ActionForm.
This works the same way.
1)ActionForm
2)Action classes
3)struts-config.xml
4)jsps
            /*ActionForm-----UploadForm.java*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mypack;

import java.util.ArrayList;
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;
    private ArrayList listFile;
    private int  index=0;
    public UploadForm() {
        System.out.println("uploadForm constructor");
        listFile=new ArrayList();
        this.index=0;
    }
    public FormFile getTheFile(int index)
    {
        return this.theFile;
    }
    public void setTheFile(int index,FormFile theFile )
    {
        System.out.println("setter");
        this.theFile=theFile;
        setListFile(theFile);
        this.index++;
    }
    public ArrayList getListFile()
    {
        return this.listFile;
    }
    public void setListFile(FormFile theFile)
    {
        this.listFile.add(index, theFile);
    }

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

/* uploadAction to save all the file over server*/

/*
 * 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 java.util.ArrayList;
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);
        ArrayList al=myform.getListFile();
         System.out.println("Pass1111>>>>>>>>>");
         System.out.println("Size of Array List:" + al.size());
         System.out.println("Entering the for loop...");
         for(int i=0;i<al.size();i++){
        
             // get file from the bean
            FormFile ff = (FormFile) al.get(i);
            String fname = ff.getFileName();
            if(fname.length()==0) {
                    continue;
            }
            System.out.println("File Name :" + fname);
            System.out.println("File Name  length:" + fname.length());

            System.out.println("file type:" + ff.getContentType());
            int size = ff.getFileSize();

            // save file in the app server
            //File newFile =  new File(getServlet().getServletContext().getRealPath("") + "/temp/" + ff.getFileName());
            File newFile=new File("c:\\upload\\"+ff.getFileName());
            if(!newFile.exists()){
            FileOutputStream fos = new FileOutputStream(newFile);
            fos.write(ff.getFileData());
            fos.close();
            }
            request.setAttribute("fileName["+i+"]",fname);

            
            
            
         }






//         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>


finally jsps::::


<%--
    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>
        <script>

var fCount = 1;
function addElement() {

fCount++;

var fObject = document.getElementById('fileSection');
var text = 'File:';
var tag='<input type="file" name="theFile[' +  fCount +  ']" value="">';
var brk='<br>'
var o1 = document.createTextNode(text);
var o2 = document.createElement(tag);
var o3 = document.createElement(brk);

   fObject.appendChild(o3);
   fObject.appendChild(o1);
   fObject.appendChild(o2);
   fObject.appendChild(o3);

  alert("fCount" + fCount);

}


</script>
        <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">

            <div id="fileSection">
            Select file to upload <html:file property="theFile[0]"/><br>
            </div>
            <html:submit>
                <bean:message key="message.upload" />
            </html:submit>
            <html:button property="bt" onclick="addElement()">Upload More files</html:button>
           
        </html:form>
    </body>
</html>



<%--
    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[0]");
            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>

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>