java压缩多个文件到zip中,并返回给浏览器

博客围绕一个需求展开,即使用Java生成Excel文件,将生成的文件压缩到Zip包中,然后响应给浏览器,还附上了可写在本地或服务器上的公共方法,并给出了核心代码。

        今天遇到个需求,需要生成excel文件,生成文件后压缩到zip包中,然后响应给浏览器,下面是核心代码,以便后面再用到:

        

/**
     * 下载压缩包,响应给浏览器
     * @param fileList  文件集合
     * @param zipFileName  下载zip的文件名
     * @param request
     * @param response
     */
    public void downloadZip(List<File> fileList,String zipFileName, HttpServletRequest request,HttpServletResponse response){
        byte[] buf = new byte[1024];
        // 获取输出流
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileInputStream in = null;
        ZipOutputStream out = null;
        try {
            // 重置
            response.reset();
            String fileName = "";
            String agent = request.getHeader("user-agent");
            if (agent.contains("FireFox")) {
                fileName = new String(zipFileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                fileName = URLEncoder.encode(zipFileName, "UTF-8");
            }

            // 不同类型的文件对应不同的MIME类型
            response.setContentType("application/x-msdownload");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".zip");

            // ZipOutputStream类:完成文件或文件夹的压缩
            out = new ZipOutputStream(bos);
            for (int i = 0; i < fileList.size(); i++) {
                in = new FileInputStream(fileList.get(i));
                // 给列表中的文件单独命名
                out.putNextEntry(new ZipEntry(fileList.get(i).getName()));
                int len = -1;
                while ((len = in.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
            out.close();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if (in != null){
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

        另外附上写在某个位置(比如本地或者服务器上)的公共方法:

 //调用示例  zipFiles(fileList.toArray(new File[fileList.size()]),new File("D:\\/my.zip"));
    /**
     * 生成压缩文件
     * @param srcFiles  要压缩的文件
     * @param zipFile   压缩包全路径
     */
    public void zipFiles(File[] srcFiles, File zipFile) {
        // 判断压缩后的文件存在不,不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 创建 FileInputStream 对象
        FileInputStream fileInputStream = null;

        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            // 遍历源文件数组
            for (int i = 0; i < srcFiles.length; i++) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                fileInputStream = new FileInputStream(srcFiles[i]);
                // 实例化 ZipEntry 对象,源文件数组中的当前文件
                zipEntry = new ZipEntry(srcFiles[i].getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Java中,你可以使用Apache Commons IO库来处理文件操作,包括读取PDF文件和创建ZIP包。以下是一个简化的示例,展示如何完成这个任务: ```java import org.apache.commons.io.IOUtils; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFileOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URL; public class PDFZipServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求中的URL列表 String[] urls = request.getParameterValues("urls"); // 假设请求中有名为"urls"的参数,包含多个PDF URL if (urls == null || urls.length == 0) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No URLs provided"); return; } try { // 创建临时目录来保存PDFs File tempDir = File.createTempFile("pdf-", ".tmp", getServletContext().getRealPath("/")); tempDir.deleteOnExit(); for (String url : urls) { downloadAndSavePdf(url, tempDir); } // 创建一个新的ZIP文件 ZipFileOutputStream zos = new ZipFileOutputStream(response.getOutputStream()); compressDirectory(zos, tempDir); // 设置响应头,表明这是一个下载 response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=compressed_pdfs.zip"); response.setContentLength(zos.size()); zos.close(); } catch (IOException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create zip file: " + e.getMessage()); } } private void downloadAndSavePdf(String url, File dir) throws IOException { URL u = new URL(url); InputStream in = u.openStream(); try { File pdfFile = new File(dir, u.getFile().substring(u.getFile().lastIndexOf("/") + 1)); IOUtils.copy(in, new FileOutputStream(pdfFile)); } finally { IOUtils.closeQuietly(in); } } private void compressDirectory(ZipFileOutputStream zos, File directory) throws IOException { File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { compressDirectory(zos, file); } else { addFileToZip(zos, file); } } } } private void addFileToZip(ZipFileOutputStream zos, File file) throws IOException { ZipArchiveEntry entry = new ZipArchiveEntry(file.getName()); zos.putArchiveEntry(entry); FileInputStream fis = new FileInputStream(file); byte[] bytesIn = new byte[1024]; int length; while ((length = fis.read(bytesIn)) > 0) { zos.write(bytesIn, 0, length); } zos.closeArchiveEntry(); fis.close(); } } ``` 在这个例子中,你需要在`doGet`方法里接收前端传递的URLs,通过`downloadAndSavePdf`函数下载每个PDF。然后,`compressDirectory`会递归地将所有下载的PDF添加到ZIP文件中。 注意,这个示例假设了PDF文件可以直接从网络下载,实际应用中可能会有权限或其他限制。另外,处理用户输入时需注意安全,防止恶意文件注入。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值