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!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM