Java实现先把多个文件压缩为zip文件后下载zip文件

Java实现请求后台后,多个Excel压缩成一个zip后,再下载zip,下载完删除压缩包。

1、添加依赖

    <!-- 下载依赖 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>
    <!-- servlet的依赖,有就不用 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

2、DownloadZip下载servlet,servlet

import javax.servlet.ServletException;
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 DownloadZip extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        //获得要下载的文件名
        String fileName = "用户表.xlsx";
        String fileName2 = "用户表1.xlsx";
        String fileSaveRootPath = "F:\develop_java\tomcat\apache-tomcat-9.0.13\webapps\ROOT\WEB-INF\classes\excel\";
        //得到要下载的文件
        File file = new File(fileSaveRootPath, fileName);
        File file2 = new File(fileSaveRootPath, fileName2);
        System.out.println("Excel文件保存路径1:" + fileSaveRootPath + fileName);
        System.out.println("Excel文件保存路径2:" + fileSaveRootPath + fileName2);
        //如果文件不存在
        if (!file.exists() || !file2.exists()) {
            request.setAttribute("message", "您要下载的资源已被删除!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }
        //先压缩
        String zipName = "下载Excel.zip";
        String zipPath = fileSaveRootPath + zipName;
        ZipOutputStream zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
        ZipEntry zEntry = new ZipEntry(file.getName());
        zipOutput.putNextEntry(zEntry);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[1024];
        int read = 0;
        while((read = bis.read(buffer)) != -1){
            zipOutput.write(buffer, 0, read);
        }
        zEntry = new ZipEntry(file2.getName());
        zipOutput.putNextEntry(zEntry);
        bis = new BufferedInputStream(new FileInputStream(file2));
        while((read = bis.read(buffer)) != -1){
            zipOutput.write(buffer, 0, read);
        }
        bis.close();
        zipOutput.close();
        //创建输出流,下载zip
        try(OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(new File(zipPath));){
            //设置响应头,控制浏览器下载该文件
            response.setHeader("Content-Type","application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment;filename="+java.net.URLEncoder.encode(zipName, "UTF-8"));
            while((read = in.read(buffer)) != -1){
                out.write(buffer, 0, read);
            }
            System.out.println("zip下载路径:"+zipPath);
        }finally {
            try {
                //删除压缩包
                File zfile = new File(zipPath);
                zfile.delete();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}

3、web.xml配置servlet,我这里没有使用框架

  <servlet>
    <servlet-name>DownloadZip</servlet-name>
    <servlet-class>com.gx.zip.DownloadZip</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownloadZip</servlet-name>
    <url-pattern>/servlet/DownloadZip</url-pattern>
  </servlet-mapping>

4、downzip.jsp下载jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>下载zip</title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/servlet/DownloadZip">下载</a>
</body>
</html>

5、message.jsp没有文件提示jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${ message }
</body>
</html>

6、测试

http://localhost:8080/downzip.jsp

 

OK!Thank you for reading!

原文地址:https://www.cnblogs.com/qq1995/p/10358970.html