Thursday 24 October 2013

How to create zip file to download in JSP- Servlet

Leave a Comment
Hye, my previous post show that how to download zip file in ASP.NET,. In this tutorial i will show the same thing, but in Jsp-Servlet.

Note : In this tutorial i will use this library :-

  • JSTL 1.1

 The JSP File

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Download File As ZIP File</title>
    </head>
    <body>
       <h1>Download File As ZIP File</h1>
        ${DownloadMessage}
        <br/>
        <form action="<c:url value="/downloadFileServletZip" />" method="post" >
            Default Path is server to download is D:\JAVA\dist\Output\
            <input type="submit" name="bDownload" value="Download Zip file"/>
        </form>
    </body>
</html>





The Servlet

 import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class downloadFileServletZip extends HttpServlet {
   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String path = "D:\\JAVA\\dist\\Output\\";
        File directory = new File(path);
        String[] files = directory.list();
       
        //check if directories have files
        if (files != null && files.length > 0) {
           
            //create zip stream
            byte[] zip = zipFiles(directory, files);
           
           
            // Sends the response back to the user / browser with zip content
            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
           
            sos.write(zip);
            sos.flush();
        }
       
        request.setAttribute("DownloadMessage", "Successfully");
        request.getRequestDispatcher("DownloadZipFile.jsp").forward(request, response);
       
    }
   
    private byte[] zipFiles(File directory, String[] files) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        byte bytes[] = new byte[4096];
       
        for (String fileName : files) {
            try (FileInputStream fis = new FileInputStream(directory.getPath()
                    + "/" + fileName);
                   
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
               
                zos.putNextEntry(new ZipEntry(fileName));
               
                int bytesRead;
                while ((bytesRead = bis.read(bytes)) != -1) {
                    zos.write(bytes, 0, bytesRead);
                }
                zos.closeEntry();
            }
        }
        zos.flush();
        baos.flush();
        zos.close();
        baos.close();
       
        return baos.toByteArray();
    }
   
   
}



The Web.xml

 <servlet-mapping>
        <servlet-name>downloadFileServletZip</servlet-name>
        <url-pattern>/downloadFileServletZip</url-pattern>
    </servlet-mapping>

 <servlet>
        <servlet-name>downloadFileServletZip</servlet-name>
        <servlet-class>sys.servlet.downloadFileServletZip</servlet-class>

</servlet>




Note : This code will throw exception Access denied if the folder  to create zip file contain subfolder.





By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.