关闭

How do I create zip file in Servlet for download?

标签: 文件打zip包zip文件读写
517人阅读 评论(0) 收藏 举报
分类:

原文链接: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>
0
0
查看评论
发表评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场

深入学习golang(4)—new与make

http://www.cnblogs.com/hustcat/p/4004889.html Go语言中的内建函数new和make是两个用于内存分配的原语(allocation primitives)。对于初学者,这两者的区别也挺容易让人迷糊的。简单的说,new只分配内存,make用...
  • leonpengweicn
  • leonpengweicn
  • 2016-12-27 21:02
  • 498

mongodb及mongoclient在win7下的编译和使用

1、导言 折腾mongodb几个小时终于有结果了。呃!现在就简单总结一下。 其实我的需求很简单,就是在C++代码中调用mongodb的库函数,也就是要得到mongoclient.lib。本来想直接下载个,可在网上也没找到,觉得重新编译也不麻烦,于是就下了源码编译。可下错了源码,编了半天也编不出来,晕...
  • BaiWfg2
  • BaiWfg2
  • 2014-07-22 17:14
  • 7990

用servlet写的一个简单的下载文件功能

文件目录 download。html源码
  • ttf1993
  • ttf1993
  • 2014-11-23 20:08
  • 1300

通用Servlet Ajax请求 /do 处理所有请求,反射机制

//我们来看下通用ajax 对应的js//其中action为系统内对应的Action类,method 对应的是类中的方法,page和id 可以为"",param为传入参数,//func为回调函数,p1-p8均为回调函数传递的参数 function callObjectAction...
  • u012055814
  • u012055814
  • 2016-08-08 17:21
  • 1121

python入门笔记--循环(for...range\enumerate\zip)、列表推导

一、循环结构 >>> range(1,5) #代表从1到5(不包含5) [1, 2, 3, 4] >>> range(1,5,2) #代表从1到5,间隔2(不包含5) [1, 3] >>> range(5) #代表从0到5(不包含5) [0, 1...
  • u011649536
  • u011649536
  • 2015-05-21 15:34
  • 3261

zoj3950——How Many Nines(日期模拟)

If we represent a date in the format YYYY-MM-DD (for example, 2017-04-09), do you know how many 9s will appear in all the dates between Y1-M1-D1 and Y...
  • blue_skyrim
  • blue_skyrim
  • 2017-04-09 22:02
  • 710

Servlet的匹配规则和顺序

1.  写法 ①完全匹配:以“/”开头,以字母(非“*”)结束    如:/test/list.do ②目录匹配:以“/”开头且以“/*”结尾    如:/test/*    /* ③扩展名匹配...
  • aman1111
  • aman1111
  • 2015-08-10 12:00
  • 3496

cocos2d热更新代码分析

cocos2d热更新代码分析#include "AssetsManagerEx.h" #include "CCEventListenerAssetsManagerEx.h" #include "deprecated/CCString.h" ...
  • keep_moving_cqu
  • keep_moving_cqu
  • 2016-05-15 00:39
  • 1642

Android热修复学习(一)

Classloader基础Classloader的简单定义: 通过类的全限定名来获取描述此类的二进制字节流,负责读取 Java 字节代码,并转换成 java.lang.Class 类的一个实例。每个类加载器都有一个父类加载器(包含的关系),顶级类加载器(native)除外。 独立的类名称空间 能...
  • xiandan87
  • xiandan87
  • 2016-06-22 16:55
  • 5903

使用puppet来实现自动化安装openstack mysql节点

想使用puppet来实现自动化安装openstack s
  • zuopaide
  • zuopaide
  • 2014-08-19 19:59
  • 4319
    个人资料
    • 访问:179541次
    • 积分:2466
    • 等级:
    • 排名:第17347名
    • 原创:48篇
    • 转载:5篇
    • 译文:0篇
    • 评论:194条
    技术交流

    Android技术讨论群

    Java Android开发技术讨论
    博客专栏
    最新评论
    百度统计