java批量下载文件并压缩

一、代码

需要hutool的api

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 自定义 (zip压缩包/文件) 操作工具类
 */
@Slf4j
@SuppressWarnings("all")
public class ZipFileUtils {



    /**
     * 生成Zip压缩包 )
     *
     * @param targetZipFile 生成zip存放的路径
     * @param sourceFiles   压缩包中包含的文件集合
     * @param dirWithFlag   是否将文件目录一同打包进去 (true:压缩包中包含文件目录,false:压缩包中不包含目录)
     */
    public static void generateZip(File targetZipFile, List<File> sourceFiles, boolean dirWithFlag) {
        if (CollUtil.isNotEmpty(sourceFiles)) {
            File[] fileArr = sourceFiles.toArray(new File[]{});
            ZipUtil.zip(targetZipFile, dirWithFlag, fileArr);
        }
    }

    /**
     * 下载ZIP压缩包(会对下载后的压缩包进行删除)
     *
     * @param file     zip压缩包文件
     * @param response 
     */
    public static void downloadZip(File file, HttpServletResponse response) {
        OutputStream toClient = null;
        try {
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            toClient = new BufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", file.getName());
            toClient.write(buffer);
            toClient.flush();
        } catch (Exception e) {
            log.error("下载zip压缩包过程发生异常:", e);
        } finally {
            if (toClient != null) {
                try {
                    toClient.close();
                } catch (IOException e) {
                    log.error("zip包下载关流失败:", e);
                }
            }
            //删除改临时zip包(此zip包任何时候都不需要保留,因为源文件随时可以再次进行压缩生成zip包)
            file.delete();
        }
    }

    /**
     * 任何单文件下载
     *
     * @param file     要下载的文件
     * @param response 响应
     */
    public static void downloadAnyFile(File file, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            // 清空response
            response.reset();
            //防止文件名中文乱码
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(),"UTF-8"));
            //根据文件动态setContentType
            response.setContentType(new MimetypesFileTypeMap().getContentType(file) + ";charset=UTF-8");
            outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while ((len = fileInputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

二、前端部分

export default {
  methods: {
   selectExportExcel() {
      this.$http({
        url: "",
        method: "get",
        params: {
          idList: this.idList
        },
        //这个不能忘!!!!  否则下载下来的文件都是损坏的!!!
        responseType: 'blob'
      }).then((response) => {
        if (!response) {
          return;
        }
        let link = document.createElement("a");
        let filename = response.headers["content-disposition"];
        if (filename.indexOf("temp") > 0) {
          link.href = filename;
        } else {
          link.href = window.URL.createObjectURL(new Blob([response.data]));
        }
        link.target = "_blank";
        link.download = decodeURI(filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
    }
  }
    }

三、调用

        List<File> files = new ArrayList<>();
        String fileName = "D:/" + System.currentTimeMillis() + ".zip";
        //获取文件的前缀
        //String baseDir = IAASProperites.newInstance().getUserfilesBaseDir();
        ZipFileUtils.generateZip(new File(fileName), files, false);
        ZipFileUtils.downloadZip(new File(fileName),response);
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值