How to create zip file to download in JSP- Servlet

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 =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico