原文链接: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. [笔记]Python的调试器pudb简易教程

    Linux下运行python脚本,pudb是一个不错的调试器. 语法高亮,断点,调用栈,命令行,都有了,如下图. [安装] pip install pudb [使用] pudb xxx.py [快捷键 ...

  2. maven 不打包hbm 问题

    <build> <resources> <resource> <directory>src/main/java</directory> &l ...

  3. 笔记——Springboot response、ServletOutputStream、图形验证码显示慢

    今天遇到一个图形验证码加载很慢的问题,大概耗时有200~500毫秒左右. 根据追踪,图形验证码图片生成耗时0~1毫秒,而response.getOutputStream.write()将图片写入前台页 ...

  4. Linux安全策略配置-pam_tally2身份验证模块

    PAM身份验证安全配置实例 - 强制使用强密码(用户密码安全配置) - 用户SSH登录失败尝试次数超出限制后锁定账户(帐户锁定/解锁和时间设置) - 允许普通用户使用sudo而不是su(限制普通用户登 ...

  5. 【Java】流与文件(端口 & 文件读写对象)

    概述: 1.input和output是相对于内存而言的.输入(input)就是写入到内存里,输出(output)就是把内存里的东西写到外面. 2.操作内存里的东西非常便利,要么声明变量,要么new对象 ...

  6. xshell 常用命令

    一.grep 命令 (1)命令格式 grep [选项] pattern [file] (2)常用参数 参数 描述 -c 计算找到 '搜寻字符串'(即 pattern) 的次数 -i 忽略大小写的不同, ...

  7. Android Gradle 构建工具(Android Gradle Build Tools)是什么?

    转载地址:http://mrfu.me/android/2015/07/17/New_Android_Gradle_Build_Tools/ 译者地址:[翻]一览新的 Android Gradle 构 ...

  8. NOIP 统计单词个数

    描述 给出一个长度不超过200的由小写英文字母组成的字母串(约定;该字串以每行20个字母的方式输入,且保证每行一定为20个).要求将此字母串分成k份(1<k<=40),且每份中包含的单词个 ...

  9. java基础(4)--运算符及表达式

    运算符及表达式 算数运算 加(+) 减(-) 乘(*)  除(/) 取余(%) 自增(++) 自减(- -) 注意点 1. 同种类型参与运算(可能需要自动类型转换),返回同种类型 2. 整数的除法是整 ...

  10. Search in Rotated Sorted Array, 查找反转有序序列。利用二分查找的思想。反转序列。

    问题描述:一个有序序列经过反转,得到一个新的序列,查找新序列的某个元素.12345->45123. 算法思想:利用二分查找的思想,都是把要找的目标元素限制在一个小范围的有序序列中.这个题和二分查 ...