文件的单文件下载、批量文件下载

package file;


import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.commons.io.file.*;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author zzl
 * @Date 2022/1/15
 * @description 1、单文件下载 2、文件批量下载压缩成zip文件
 */
public class SingleDownLoadFile {
    public static void main(String[] args) {
        String sourcePath = "E:\\fileTest\\send\\test.txt";
        String targetPath = "E:\\fileTest\\get";
        try {
            // 测试单文件下载
            HttpServletResponse response = null;
            // byte[] bytes = singDownLoadFile(sourcePath, targetPath, response);
            // System.out.println(bytes);

            // 测试多文件下载
            List<String> fileList = new ArrayList<>();
            fileList.add("E:\\fileTest\\get\\test.txt");
            fileList.add("E:\\fileTest\\get\\test2.txt");
            byte[] bytes = downloadZipFiles(fileList, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 模拟下载文件:直接
     * 实际的话,根据源文件路径,拿到源文件的二进制文件byte,将文件的名字封装在header中,前端根据name以及byte文件下载下来即可
     *
     * @param sourcePath 源文件路径
     * @param targetPath 目标文件路径
     * @return
     */
    public static byte[] singDownLoadFile(String sourcePath, String targetPath, HttpServletResponse response) throws Exception {

        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            throw new Exception("sourcepath is not exists");
        }
        FileInputStream fis = new FileInputStream(sourceFile);

        File targetFile = new File(targetPath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(targetFile + "\\" + sourceFile.getName());
        response.setHeader("Content-Disposition", "attachment;Filename=" + sourceFile.getName());
        byte[] bytes = new byte[9086];
        int temp = 0;
        while ((temp = fis.read(bytes)) != -1) {
            fos.write(bytes, 0, temp);
        }
        fos.close();
        fis.close();
        return bytes;
    }

    /**
     * 模拟批量文件压缩zip文件下载
     * 实际中,将批量文件压缩成zip文件,将zip文件的二进制流byte数组返回至前端即可以下载
     * 将压缩文件名放与响应头部,前端拿到该名字去下载压缩文件
     *
     * @param fileList
     * @return
     */
    public static byte[] downloadZipFiles(List<String> fileList, HttpServletResponse response) {
        byte[] zipByte = null;
        File tempFile = null;
        ZipOutputStream zos = null;
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            // 临时路径
            String tempPath = System.getProperty("user.dir") + "\\zip\\";
            File createPath = new File(tempPath);
            if (!createPath.exists()) {
                tempFile.mkdir();
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String path = tempPath + format.format(new Date()) + ".zip";
            tempFile = new File(path);
            tempFile.createNewFile();
            // 文件输出流
            fos = new FileOutputStream(tempFile);
            // 压缩文件输出流
            zos = new ZipOutputStream(fos);
            if (!CollectionUtils.isEmpty(fileList)) {
                for (String sourcePath : fileList) {
                    File sourceFile = new File(sourcePath);
                    fis = new FileInputStream(sourceFile);
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    zos.putNextEntry(new ZipEntry(sourceFile.getName()));
                    while ((len = fis.read()) != -1) {
                        zos.write(len);
                    }
                }
            }
            zipByte = org.apache.commons.io.FileUtils.readFileToByteArray(tempFile);
            response.setHeader("Content-Disposition", "attachment;filename=" + tempFile.getName());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (zos != null) {
                    zos.closeEntry();
                    zos.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (fis != null) {
                    fis.close();
                }
                // 删除临时文件,测试时,可以将其屏蔽,看到生成的压缩文件
                FileUtils.forceDelete(tempFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return zipByte;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值