1. 程式人生 > 實用技巧 >java批量下載檔案為zip包

java批量下載檔案為zip包

批量下載檔案為zip包的工具類

package com.meeno.trainsys.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @description: 批量下載檔案
 * @author: Wzq
 * @create: 2019-11-25 10:17
 */
public class BatchDownFilesUtils {

    /**
    *@Description 輸入檔案集合,zipPath臨時路徑,request,response匯出zip檔案
    *@Param [files, zipPath, request, response]
    *@Return javax.servlet.http.HttpServletResponse
    *@Author Wzq
    *@Date 2019/11/25
    *@Time 19:49
    */
    public static HttpServletResponse downLoadFiles(List<File> files,
                                                    String zipPath,
                                                    HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            /**這個集合就是你想要打包的所有檔案,
             * 這裡假設已經準備好了所要打包的檔案
             */

            //List<File> files = new ArrayList<File>();

            /**建立一個臨時壓縮檔案,
             * 我們會把檔案流全部注入到這個檔案中
             * 這裡的檔案你可以自定義是.rar還是.zip
                     * 這裡的file路徑釋出到生產環境時可以改為
             */
            File file = new File(zipPath);
            if (!file.exists()){
                file.createNewFile();
            }
            response.reset();
            //response.getWriter()
            //建立檔案輸出流
            FileOutputStream fous = new FileOutputStream(file);
            /**打包的方法我們會用到ZipOutputStream這樣一個輸出流,
             * 所以這裡我們把輸出流轉換一下*/
            //            org.apache.tools.zip.ZipOutputStream zipOut
            //                = new org.apache.tools.zip.ZipOutputStream(fous);
            ZipOutputStream zipOut
                    = new ZipOutputStream(fous);
            /**這個方法接受的就是一個所要打包檔案的集合,
             * 還有一個ZipOutputStream
             */
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file,response);
        }catch (Exception e) {
            e.printStackTrace();
        }
        /**直到檔案的打包已經成功了,
         * 檔案的打包過程被我封裝在FileUtil.zipFile這個靜態方法中,
         * 稍後會呈現出來,接下來的就是往客戶端寫資料了
         */
        // OutputStream out = response.getOutputStream();


        return response ;
    }

    /**
     * 把接受的全部檔案打成壓縮包
     * @param List<File>;
     * @param org.apache.tools.zip.ZipOutputStream
     */
    private static void zipFile
    (List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }
    
    /**
    *@Description 下載zip檔案,刪除快取檔案
    *@Param [file, response]
    *@Return javax.servlet.http.HttpServletResponse
    *@Author Wzq
    *@Date 2019/11/25
    *@Time 19:48
    */
    private static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        try {
            // 以流的形式下載檔案。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }finally{
            try {
                File f = new File(file.getPath());
                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 根據輸入的檔案與輸出流對檔案進行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    private static void zipFile(File inputFile,
                               ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                /**如果是目錄的話這裡是不採取操作的,
                 * 至於目錄的打包正在研究中
                 */
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向壓縮檔案中輸出資料
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 關閉建立的流物件
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

使用批量下載方法

在controller程式碼層使用批量下載工具類中的方法,把多個file檔案打包成zip下載!

  List<File> fileList = Lists.newArrayList(); //檔案的集合
  String zipFilePath = "E:\test\xxx.zip"; //zip快取的位置,方法工具類中方法下載完成後刪除快取zip
  BatchDownFilesUtils.downLoadFiles(fileList,zipFilePath,request,response); //呼叫下載方法