Java 多文件打包压缩包进行导出下载

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

public class ZipUtils{
    /**
     * @author  wj
     * @description 批量导出下载文件,多个文件为压缩包,单个为文件本身
     * @date 2023/10/27 16:59
     * @param response: response
     * @param filePathList: 文件本地全地址列表
     * @param zipName:  导出的压缩包名称,后面会自动加上时间
     */
    public static void downLoadFile(HttpServletResponse response,List<String> filePathList,String zipName) throws Exception {
        if(filePathList.size() == 1){
            //只存在一个附件时直接下载对应附件
            File file = new File(filePathList.get(0));
            if(!file.exists()){
                throw new Exception("文件不存在");
            }
            //输出文件流
            writeFileToRes(response, file.getName(), file);
        }else if(filePathList.size() > 1){
            //压缩文件
            File file = compressedFileToZip(zipName, filePathList);
            //输出文件流
            writeFileToRes(response, file.getName(), file);
            //删除压缩包
            if(file.exists()){
                file.delete();
            }
        }
    }

    /**
     * 压缩文件
     * @param datumName 压缩包名称
     * @param filePathList 附件路径
     * @return File
     * @throws Exception Exception
     */
    private static File compressedFileToZip(String datumName, List<String> filePathList) throws Exception {
        //压缩包具体名称(拼接时间戳防止重名)
        String zipFileName = datumName + "-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
        //生成压缩包存储地址(最后会删掉)
        String fileZip = "D:/" + zipFileName;
        OutputStream os=null;
        ZipOutputStream zos = null ;
        File file = new File(fileZip);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os=new FileOutputStream(file);
            //压缩文件
            zos = new ZipOutputStream(os);
            byte[] buf = new byte[1024];
            for (String filePath : filePathList) {
                File tempFile = new File(filePath);
                //在压缩包中添加文件夹
                //zos.putNextEntry(new ZipEntry("测试/"+tempFile.getName()));
                //直接在压缩包中添加文件
                zos.putNextEntry(new ZipEntry(tempFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(tempFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("文件打包:"+e.getMessage());
        }finally {
            //关闭流
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭流
            if(os!= null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    /**
     * 输出文件流到response
     * @param response response
     * @param fileName fileName
     * @param file file
     * @throws IOException IOException
     */
    private static void writeFileToRes(HttpServletResponse response, String fileName, File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("application/octet-stream");
        //2.设置文件头:最后一个参数是设置下载文件名
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.addHeader("Content-Length", "" + file.length());

        //3.通过response获取ServletOutputStream对象(out)
        ServletOutputStream out = response.getOutputStream();

        int b = 0;
        byte[] buffer = new byte[1024];
        while (b != -1) {
            b = inputStream.read(buffer);
            //4.写到输出流(out)中
            out.write(buffer, 0, b);
        }
        out.flush();
        out.close();
        inputStream.close();

    }

}

原文链接:java下载文件(多个文件进行打包下载)_java下载多个文件后打包下载_ycblog.top的博客-CSDN博客

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解压失败可能有多种原因,以下是一些可能的原因和解决方法: 1. 压缩包损坏:首先,检查下载压缩包是否完整且没有损坏。可以尝试重新下载压缩包,并确保下载过程中没有中断或出错。 2. 压缩包格式不受支持:确保使用的解压工具支持压缩包的格式。常见的压缩格式ZIP、RAR、7z等。如果使用的解压工具不支持该格式,可以尝试使用其他支持该格式的工具。 3. 解压路径权限问题:检查解压路径是否具有足够的权限来解压文件。如果解压路径是受限制的目录,可能需要以管理员身份运行解压工具或将解压路径更改为具有适当权限的目录。 4. 解压工具版本问题:有时,解压工具的版本可能不兼容压缩包。尝试更新解压工具到最新版本,并再次尝试解压文件。 5. 文件名或路径含非法字符:检查压缩包中的文件名和路径是否含非法字符,例如特殊字符或空格。尝试将压缩包解压到一个简单的路径,例如根目录或没有特殊字符的文件夹。 如果以上方法都无法解决问题,可能需要进一步调查压缩包的来源和内容,以确定是否存在其他问题。 #### 引用[.reference_title] - *1* *2* *3* [Java操作文件的日常总结(文件压缩,文件解压,递归删除文件文件下载保存)](https://blog.csdn.net/u014534808/article/details/125111422)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值