Thursday, March 4, 2010

Display the contents of a Zip file

package com.jijo.servlet;

import java.io.*;
import java.util.zip.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ZipView extends HttpServlet
{
    /**
     * Display the contents of a zip file
     */
    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
        try
        {
            String zipFile = request.getParameter("fileNames");//specify the zip file           
            response.setContentType("text/html"); 
            PrintWriter out = response.getWriter();
            out.println("<table><tr><th>File Name</th><th>Size</th><th>Date </th><th>Compressed Size</th></tr>");
            if(zipFile != null && zipFile.trim().length()>0){
               
                //BufferedOutputStream out = null;
                ZipInputStream  in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)));
                ZipEntry entry;
                while((entry = in.getNextEntry()) != null)
                {
                    out.println("<tr><td>"+ entry.getName()+"</td><td>"+ entry.getSize()+"</td><td>"+ entry.getTime() +" </td><td>"+ entry.getCompressedSize() +" </td></tr>");
                    /*System.out.println(entry.getName());
                    int count;
                    byte data[] = new byte[1000];
                    out = new BufferedOutputStream(new FileOutputStream("C:/pdf/out.txt"),1000);
                    while ((count = in.read(data,0,1000)) != -1)
                    {
                        out.write(data,0,count);
                    }
                    out.flush();
                    out.close();
                    */
                }               
            }
            out.println("</table>");       
            out.flush();
            out.close();           
           
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    } 
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   }

//Put the servlet entry in web.xml file

Download selected files as Zip

package com.jijo.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author jijo
 * This servlet class is used to download the list files as a zip
 */
public class ZipDownload extends HttpServlet{
    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        byte[] files = null;
       
        try {
            String random = this.generateRamdomCode(10, 15);
           //Specify the files names seperated by '@!'
            String reqFile = request.getParameter("fileNames");
            if(reqFile != null && reqFile.trim().length()>0){
                String filenames[] = reqFile.split("@!");   
               
                ZipOutputStream zipFile = new ZipOutputStream(new FileOutputStream(random + ".zip"));
                for (String filename : filenames) {
                    try{
                        filename = filename.trim();
                        if(filename.length()>0){
                            FileInputStream fin = new FileInputStream(filename);
                            File file = new File(filename);
                            zipFile.putNextEntry(new ZipEntry(filename.substring(filename
                                    .lastIndexOf("/") + 1, filename.length())));
                            files = new byte[(int) file.length()];
                            fin.read(files);
                            zipFile.write(files);
                            fin.close();
                            zipFile.closeEntry();
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                zipFile.close();
                FileInputStream zip = new FileInputStream(random + ".zip");
                File f = new File(random + ".zip");
                files = new byte[(int) f.length()];
                zip.read(files);
                zip.close();
                f.delete();           
               
                //response
                response.setContentType("application/zip");
                response.setContentLength(files.length);
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"jijo.zip\"");
                try {
                    response.getOutputStream().write(files);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
           
        }
    }

    private String generateRamdomCode(double min, double max){
        String code = "";
        int totalChars = (int)((Math.random() * min)+max);
        char startChar = 'A';
        for(int i=0;i<totalChars;i++){
            int selNum = (int)(Math.random() * 13.0);
           
            if(selNum <= 4){
                startChar = 'A';
                code += (char)((Math.random()*26.0)+startChar);
            }else if(selNum >=5 && selNum<= 9){
                code += (int)(Math.random() * 10.0);
            }else if(selNum >=10){
                startChar = 'a';
                code += (char)((Math.random()*26.0)+startChar);
            }
        }
        System.out.println(code);
        return code;
    }   
   
}

Put the servlet entry and url mapping in web.xml file.

Display or download Files using servlet

/**
 *
 */
package com.jijo.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jijo
 * This servlet class is used to display or download the file
 *
 */
public class DownloadFile extends HttpServlet{
   
   
   
    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {
        doPost(request, response);
    }
   
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        ServletOutputStream outputStream = null;
        InputStream input = null;
       
        try {
            outputStream = response.getOutputStream();
            String filePath = request.getParameter("fileNames");  //filepath
            if(filePath != null && filePath.trim().length()>0){               
                String download = request.getParameter("download");//download or display
                File prefile = new File(filePath);
                byte buff[] = new byte[8192];
                input = new FileInputStream(prefile);
                String contenttype = filePath.substring(filePath.lastIndexOf(".")+1, filePath.length());
                contenttype = contenttype.toLowerCase();
               
                if(download != null && download.trim().length()>0){
                      response.setContentType("application/octet-stream");
                }
                else{
                    if (contenttype != null) {
                        String responseType = getResponseContentType(contenttype);
                        response.setContentType(responseType);                        
                    } else {
                        response.setContentType("application/octet-stream");
                    }
                }          
                response.setHeader("Content-Length", String.valueOf(prefile.length()));          
                if(download != null && download.trim().length()>0){
                    response.setHeader("Content-Disposition","attachment; filename=\""+ prefile.getName()+"\"");
                }
                else{
                    response.setHeader("Content-disposition", (new StringBuilder("inline; filename=")).append(prefile.getName()).toString());
                }
                response.addHeader("Cache-Control", "no-transform, max-age=0");  
                int i = 0;
                while ((i = input.read(buff)) > 0) {
                    outputStream.write(buff, 0, i);
                    outputStream.flush();
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (input != null)
                input.close();
            if (outputStream != null)
                outputStream.close();
        }
    }
    private String getResponseContentType(String contenttype){
        String responseType = "";
        if(contenttype.indexOf("doc")>-1){
            responseType = "application/vnd.ms-word";
        }
        if(contenttype.indexOf("rtf")>-1){
            responseType = "application/rtf";
        }
        else if(contenttype.indexOf("xls")>-1){
            responseType = "application/vnd.ms-excel";
        }   
        else if(contenttype.indexOf("ppt")>-1){
            responseType = "application/ppt";
        }
        else if(contenttype.indexOf("xml")>-1){
            responseType = "text/xml";
        }
        else if(contenttype.indexOf("html")>-1){
            responseType = "text/html"; 
        }
        else if(contenttype.indexOf("htm")>-1){
            responseType = "text/htm"; 
        } 
        else if(contenttype.indexOf("txt")>-1 || contenttype.indexOf("log")>-1){
            responseType = "text/plain";
        }   
        else if(contenttype.indexOf("pdf")>-1){
            responseType = "application/pdf";
        }
        else if(contenttype.indexOf("gif")>-1){
            responseType = "image/gif";
        }
        else if(contenttype.indexOf("png")>-1){
            responseType = "image/png";
        }
        else if(contenttype.indexOf("jpg")>-1){
            responseType = "image/jpg";
        }
        else if(contenttype.indexOf("jpeg")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("jpe")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("bmp")>-1){
            responseType = "image/bmp";
        }
        else if(contenttype.indexOf("jpeg")>-1){
            responseType = "image/JPEG";
        }
        else if(contenttype.indexOf("tiff")>-1){
            responseType = "image/tiff";
        }
        else if(contenttype.indexOf("tif")>-1){
            responseType = "image/tiff";
        }       
        else if(contenttype.indexOf("html")>-1){
            responseType = "text/html";
        }
        else{
            responseType = "application/octet-stream";
        }
        return responseType;
    }
   
}




in web.xml


<servlet>
        <servlet-name>ViewFile</servlet-name>
        <servlet-class>com.jijo.servlet.DownloadFile</servlet-class>
    </servlet>   
    <servlet-mapping>
        <servlet-name>ViewFile</servlet-name>
        <url-pattern>*.viewfile</url-pattern>
    </servlet-mapping>


    <mime-mapping>
        <extension>pptx</extension>
        <mime-type>
            application/vnd.openxmlformats-officedocument.presentationml.presentation
        </mime-type>
    </mime-mapping>
   
    <mime-mapping> 
        <extension>docx</extension> 
         <mime-type>application/vnd.openxmlformats-officedocument.wordprocessingml.document</mime-type> 
     </mime-mapping> 
     <mime-mapping> 
        <extension>xlsx</extension> 
        <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type> 
     </mime-mapping> 




in jsp

<form name='form1' method="post" action="file.viewfile" target="fileframe"/>
<input type='hidden' name='fileNames' id='fileNames' value='C:/jijo/resume.txt'/>
<input type='hidden' name='download' id='download' value='true'/>//set as blank when u want to display
<input type='Submit' name='Submit' id='Submit' value='Display'/>
</form>
<frame name="fileframe" id="fileframe"></frame>