java 将文件附件打包成zip并下载

该代码段展示了一个SpringBoot控制器方法,用于处理文件下载请求。首先,它从BusinessClaims对象中获取文件附件信息,然后将URL转换为File对象,并将这些文件添加到一个列表中。接着,设置HTTP响应头以触发文件下载,并使用ZipUtils工具类将文件列表打包成ZIP压缩包进行下载。最后,删除生成的临时文件。
摘要由CSDN通过智能技术生成
Controller

@PostMapping("/download")
public void download(HttpServletResponse response, @RequestBody BusinessClaims businessClaims) throws IOException {
    // 文件附件查询
    AjaxResult attachment = businessClaimsService.attachment(businessClaims);
   List<SysFile> data1 = (List<SysFile>) attachment.get("data");
    List<File> fileList = new ArrayList<>();
//获取文件名之类的 
    for (SysFile sysFile : data1) {
        String filePath = sysFile.getFilePath();
        String fileSuffix = sysFile.getFileSuffix();
        String fileOldName = sysFile.getFileOldName();
        File fileByUrl = getFileByUrl(filePath, fileSuffix,fileOldName);
        fileList.add(fileByUrl);
    }
    response.setHeader("content-type", "application/octet-stream");
    response.setContentType("application/octet-stream");
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");
    ZipUtils.downloadZip(response.getOutputStream(), fileList);
}


工具类
//url转file
private File getFileByUrl(String fileUrl, String suffix,String name) {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    BufferedOutputStream stream = null;
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    File file = new File(name);
    try {
        URL imageUrl = new URL(fileUrl);
        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        inputStream = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        File file1 = File.createTempFile("zxczzzzzz", suffix);
        file1.renameTo(file);
        fileOutputStream = new FileOutputStream(file);
        stream = new BufferedOutputStream(fileOutputStream);
        stream.write(outStream.toByteArray());
    } catch (Exception e) {
    } finally {
        try {
            if (fileOutputStream != null)
                fileOutputStream.close();
            if (inputStream != null)
                inputStream.close();
            if (stream != null)
                stream.close();
            outStream.close();
        } catch (Exception e) {
        }
    }
    return file;
}




zip 工具类
package com.trustlinksop.common.core.utils.zip;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.springframework.util.FileCopyUtils.BUFFER_SIZE;

/**
 * @Author: Wenbo
 * @Date: 2023/03/02/11:03
 */
public class ZipUtils {
    /**
     * 把文件集合打成zip压缩包
     * @param srcFiles 压缩文件集合
     * @param zipFile  zip文件名
     * @throws RuntimeException 异常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws IOException {
        if(zipFile == null){
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = new FileOutputStream(zipFile);
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                // 读取文件并写入到zip中
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                    zos.flush();
                }
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (zos != null) {
                zos.close();
            }
        }
    }

    public static void downloadZip(OutputStream outputStream, List<File> fileList){
        BufferedInputStream bufferedInputStream = null;
        ZipOutputStream zipOutputStream = null;
        FileInputStream in = null;
        try {
            zipOutputStream = new ZipOutputStream(outputStream);
            for (File file : fileList) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buf = new byte[BUFFER_SIZE];
                int len;
                in = new FileInputStream(file);
                while ((len = in.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, len);
                    zipOutputStream.flush();
                }

            }
            zipOutputStream.flush();
            zipOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (in != null) {
                    System.gc();
                    in.close();
                }
                if (bufferedInputStream != null) {
                    System.gc();
                    bufferedInputStream.close();
                }
                if (zipOutputStream != null ) {
                    System.gc();
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    System.gc();
                    outputStream.close();
                }
                if (fileList != null) {
                    try {
                        Thread.currentThread().sleep(500);
                        for (File file : fileList) {
                            System.gc();
                            boolean delete = file.delete();
                            System.out.println("delete = " + delete);
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}


文章思路 先读取出 附件集合 然后 再将url 转为file 文件 再重命名 然后再 通过zip下载 然后删掉本地改名之后的file

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值