SpringBoot文件批量zip打包下载

平时开发中文件的上传下载经常会遇到,如excel的上传下载等,Excel的处理可以使用阿里的EasyExcel,一款快速、简单避免OOM的java处理Excel工具,github:https://github.com/alibaba/easyexcel, 有兴趣的可以自己去尝试下;

此处介绍文件的批量下载, 如果一次性下载多个文件的话, 建议生成文件后将文件打成ZIP包,再下载,Java代码如下:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;


public class ZipDownloadUtil {

    private static final Logger logger = LoggerFactory.getLogger(ZipDownloadUtil.class);

    /**
     * 获取当前系统的临时目录
     */
    private static final String FILE_PATH = System.getProperty("java.io.tmpdir") + File.separator;

    private static final int ZIP_BUFFER_SIZE = 8192;

    /**
     * zip打包下载
     *
     * @param response
     * @param zipFileName
     * @param fileList
     */
    public static void zipDownload(HttpServletResponse response, String zipFileName, List<File> fileList) {
        // zip文件路径
        String zipPath = FILE_PATH + zipFileName;
        try {
            //创建zip输出流
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath))) {
                //声明文件集合用于存放文件
                byte[] buffer = new byte[1024];
                //将文件放入zip压缩包
                for (int i = 0; i < fileList.size(); i++) {
                    File file = fileList.get(i);
                    try (FileInputStream fis = new FileInputStream(file)) {
                        out.putNextEntry(new ZipEntry(file.getName()));
                        int len;
                        // 读入需要下载的文件的内容,打包到zip文件
                        while ((len = fis.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }
                        out.closeEntry();
                    }
                }
            }
            //下载zip文件
            downFile(response, zipFileName);
        } catch (Exception e) {
            logger.error("文件下载出错", e);
        } finally {
            // zip文件也删除
            fileList.add(new File(zipPath));
            deleteFile(fileList);
        }
    }


    /**
     * 文件下载
     *
     * @param response
     * @param zipFileName
     */
    private static void downFile(HttpServletResponse response, String zipFileName) {
        try {
            String path = FILE_PATH + zipFileName;
            File file = new File(path);
            if (file.exists()) {
                try (InputStream ins = new FileInputStream(path);
                     BufferedInputStream bins = new BufferedInputStream(ins);
                     OutputStream outs = response.getOutputStream();
                     BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
                    response.setContentType("application/x-download");
                    response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
                    int bytesRead = 0;
                    byte[] buffer = new byte[ZIP_BUFFER_SIZE];
                    while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
                        bouts.write(buffer, 0, bytesRead);
                    }
                    bouts.flush();
                }
            }
        } catch (Exception e) {
            logger.error("文件下载出错", e);
        }
    }

    /**
     * 删除文件
     *
     * @param fileList
     * @return
     */
    public static void deleteFile(List<File> fileList) {
        for (File file : fileList) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}

 

SpringBoot项目(https://blog.csdn.net/angellee1988/article/details/82712182)web层代码:

@RestController
public class FileUploadController {
   
    @RequestMapping(value = "zipDownload", method = RequestMethod.GET)
    public String zipDownload(HttpServletRequest request, HttpServletResponse response) {
        List<File> files = new ArrayList<>();
        files.add(new File("D:\\demo1.xlsx"));
        files.add(new File("D:\\demo2.xlsx"));
        ZipDownloadUtil.zipDownload(response, "demo.zip", files);
        return "download success";
    }

}

 

 

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
ZipOutputStream是Java中一个用于压缩文件的类。它可以将多个文件或文件夹压缩成一个zip文件,并且可以设置压缩级别、密码等选项。 下面是一个简单的例子,展示如何使用ZipOutputStream将一个文件夹中的所有文件压缩成一个zip文件: ```java import java.io.*; import java.util.zip.*; public class ZipDirectory { public static void main(String[] args) throws IOException { String inputFolder = "/path/to/input/folder"; String outputZipFile = "/path/to/output/zipfile.zip"; // 创建输出流 FileOutputStream fos = new FileOutputStream(outputZipFile); ZipOutputStream zos = new ZipOutputStream(fos); // 遍历文件夹中的所有文件,并逐一添加到ZipOutputStream中 File folder = new File(inputFolder); for (File file : folder.listFiles()) { if (!file.isDirectory()) { addToZipFile(file, zos); } } // 关闭输出流 zos.close(); fos.close(); } private static void addToZipFile(File file, ZipOutputStream zos) throws IOException { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zos.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zos.write(bytes, 0, length); } zos.closeEntry(); fis.close(); } } ``` 在上面的例子中,我们首先创建了一个ZipOutputStream,然后遍历指定的文件夹中的所有文件,并使用addToZipFile()方法将每个文件逐一添加到ZipOutputStream中。在addToZipFile()方法中,我们首先创建一个ZipEntry对象,指定要添加到zip文件中的文件名,然后读取文件的内容,并将其写入ZipOutputStream中。最后,我们关闭ZipEntry和FileInputStream。 需要注意的是,ZipOutputStream只能压缩文件,不能压缩文件夹本身。如果要压缩整个文件夹,必须遍历文件夹中的所有文件,并将它们逐一添加到ZipOutputStream中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值