原文链接:https://kodejava.org/how-do-i-create-zip-file-in-servlet-for-download/

The example below is a servlet that shows you how to create a zip file and send the generated zip file for user to download. The compressing process is done by the zipFiles method of this class.

For a servlet to work you need to configure it in the web.xml file of your web application which can be found after the code snippet below.

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipDownloadServlet extends HttpServlet {
    public static final String FILE_SEPARATOR = System.getProperty("file.separator");

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            //
            // The path below is the root directory of data to be
            // compressed.
            //
            String path = getServletContext().getRealPath("data");

            File directory = new File(path);
            String[] files = directory.list();

            //
            // Checks to see if the directory contains some files.
            //
            if (files != null && files.length > 0) {

                //
                // Call the zipFiles method for creating a zip stream.
                //
                byte[] zip = zipFiles(directory, files);

                //
                // Sends the response back to the user / browser. The
                // content for zip file type is "application/zip". We
                // also set the content disposition as attachment for
                // the browser to show a dialog that will let user
                // choose what action will he do to the sent content.
                //
                ServletOutputStream sos = response.getOutputStream();
                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment; filename="DATA.ZIP"");

                sos.write(zip);
                sos.flush();
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Compress the given directory with all its files.
     */
    private byte[] zipFiles(File directory, String[] files) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        byte bytes[] = new byte[2048];

        for (String fileName : files) {
            FileInputStream fis = new FileInputStream(directory.getPath() +
                ZipDownloadServlet.FILE_SEPARATOR + 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();
            bis.close();
            fis.close();
        }
        zos.flush();
        baos.flush();
        zos.close();
        baos.close();

        return baos.toByteArray();
    }
}

The web.xml configuration:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">
    <servlet>
        <servlet-name>ZipDownloadServlet</servlet-name>
        <servlet-class>org.kodejava.example.servlet.ZipDownloadServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>ZipDownloadServlet</servlet-name>
        <url-pattern>/zipservlet</url-pattern>
    </servlet-mapping>
</web-app>

How do I create zip file in Servlet for download?的更多相关文章

  1. Java ZIP File Example---refernce

    In this tutorial we are going to see how to ZIP a file in Java. ZIP is an archive file format that e ...

  2. How do I create a zip file?(转)

    Creating a zip file is a task that can easily be accomplished by using the classes ZipOutputStream a ...

  3. How to create a zip file in NetSuite SuiteScript 2.0 如何在现有SuiteScript中创建和下载ZIP压缩文档

    Background We all knows that: NetSuite filecabinet provided a feature to download a folder to a zip ...

  4. javax.imageio.IIOException: Can't create cache file!

    javax.imageio.IIOException: Can't create cache file! at javax.imageio.ImageIO.createImageInputStream ...

  5. zip file 压缩文件

    有时候我们希望 upload 文件后自动压缩, 可以节省空间. 可以使用微软提供的压缩代码 Install-Package System.IO.Compression.ZipFile -Version ...

  6. 【POI】解析xls报错:java.util.zip.ZipException: error in opening zip file

    今天使用POI解析XLS,报错如下: Servlet.service() for servlet [rest] in context with path [/cetBrand] threw excep ...

  7. ionic build Android错误记录 error in opening zip file

    0.写在前头 运行 :cordova requirements Requirements check results for android: Java JDK: installed 1.8.0 An ...

  8. 记一个mvn奇怪错误: Archive for required library: 'D:/mvn/repos/junit/junit/3.8.1/junit-3.8.1.jar' in project 'xxx' cannot be read or is not a valid ZIP file

    我的maven 项目有一个红色感叹号, 而且Problems 存在 errors : Description Resource Path Location Type Archive for requi ...

  9. linux下解压大于4G文件提示error: Zip file too big错误的解决办法

    error: Zip file too big (greater than 4294959102 bytes)错误解决办法.zip文件夹大于4GB,在centos下无法正常unzip,需要使用第三方工 ...

随机推荐

  1. Web框架(Day64)

    阅读目录 http协议 web应用与web框架 一.http协议 HTTP协议是Hyper Text Transfer Protocol(超文本传输协议)的缩写,是用于从万维网(WWW:World W ...

  2. java 创建包含枚举的常量类

    参考 public class Constants { public static enum ServiceStatus{ NORMAL(1,"正常办理"),CHANGEING(2 ...

  3. python约束 与MD5加密写法

    python 中约束写法有两种 1 常用的通过继承关系主动抛出异常  2 通过抽象类+抽象方法 1 常用的通过继承关系主动抛出异常写法 在本send方法中报错不会抛出异常, class BaseMes ...

  4. Python 中的条件运算符

    一.概述 在 C.Java 等语言中,有一种常见的条件运算符,又叫"三目运算符". 详情参见 [条件运算符-wikipedia][https://zh.wikipedia.org/ ...

  5. HDU - 6386 Age of Moyu 2018 Multi-University Training Contest 7 (Dijkstra变型)

    题意:N个点M条边的无向图,每条边都有属于自己的编号,如果一条路径上的边编号都相同,那么花费仅为1:改变至不同编号的路径,花费加1,无论这个编号之前是否走过. 分析:记录每个点的最小花费,再用set维 ...

  6. Java 基础总结(二)

    本文参见:http://www.cnblogs.com/dolphin0520/category/361055.html 1. 字节流与和字符流 1). 字符流操作时使用了缓冲区,而在关闭字符流时会强 ...

  7. Scala:scala的一些简单操作命令

    Scala是一门多范式的编程语言,一种类似java的编程语言,设计初衷是实现可伸缩的语言.并集成面向对象编程和函数式编程的各种特性. 不太久之前编程语言还可以毫无疑意地归类成“命令式”或者“函数式”或 ...

  8. 逆序对算法(reverse pair)

    逆序对(reverse-pair) 思想和归并排序的思想一样,时间复杂度是O(nlgn). 就是在统计逆序对个数的表达式需要注意一下. 具体实现 #include <iostream> # ...

  9. painting fence - 分治 - Codeforces 448c

    2017-08-02 14:27:18 writer:pprp 题意: • 每块木板宽度均为1,高度为h[i] • n块木板连接为宽度为n的栅栏 • 每次可以刷一横或一竖(上色) • 最少刷多少次可以 ...

  10. secureCRT7.3.4的破解与安装

    1-9为 SecureCRT 7.3.4 安装图解:10-13是 SecureCRT 7.3.4 破解图解,心急的朋友可以直接向下拉. 以下是百度百科对 SecureCRT 的介绍: SecureCR ...