Java 多个文件压缩下载

本文介绍了一种实现多个文件批量下载的方法,通过将多个文件压缩成一个ZIP文件进行下载,提高了用户体验。文中提供了具体的Java代码示例,包括单个文件下载、多个文件打包下载以及自定义文件名等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了
首先下面这段代码是正常的单个下载

public void Download(@RequestParam("file_path") String file_path, HttpServletResponse response) {
        logger.info("try to download  file, the filePath : " + file_path);
        int i = file_path.lastIndexOf("/");
        String filename = file_path.substring(i+1);
        try {
           BufferedInputStream in=new BufferedInputStream(ossFileUtil.getFile(file_path));
           BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知浏览器以附件形式下载
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
           byte[] car=new byte[1024];
           int L=0;
           while((L=in.read(car))!=-1){
               out.write(car, 0,L);
           }
           if(out!=null){
               out.flush();
               out.close();
           }
           if(in!=null){
               in.close();
           }
        } catch (IOException e) {
            logger.error("the download file error :" + e.getMessage());
            throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
        }
    }

下面代码是打包下载

    public void serverDownloads(@RequestParam("file_path") String file_path,
                                @RequestParam(name = "download_name", required = false) String download_name,
                                HttpServletResponse response) throws IOException {
        logger.info("try to download server file, the filePath : " + file_path);
        String[] paths = file_path.split(",\\$\\$,");
        if(paths.length > 1){
            // 打包的文件名
            String packageName;
            if (download_name != null && download_name.trim().length() > 0) {
                packageName = download_name + ".zip";
            } else {
                packageName = "file.zip";
            }
            //打包下载
            response.setContentType("APPLICATION/OCTET-STREAM");
//          response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(packageName,"utf-8"));
            response.setHeader("Content-Disposition","attachment;filename=" + packageName);
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            try {
                int j = 1;
                for(String path : paths){
                    int i = path.lastIndexOf("/");
                    String filename = path.substring(i+1);
                    ZipUtils.doZip(remoteFileUtil.getFile(path), out, filename);
                    response.flushBuffer();
                    j++;
                }
            } catch (IOException e) {
                logger.error("the download file error :" + e.getMessage());
                throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
            }finally{
                  out.close();
            }
        }else{
            int i = file_path.lastIndexOf("/");
            String filename = file_path.substring(i+1);
            try {
                BufferedInputStream in=new BufferedInputStream(remoteFileUtil.getFile(file_path));    //BufferedInputStream(InputStream in)
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                //通知浏览器以附件形式下载
//              response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(filename,"utf-8"));
                response.setHeader("Content-Disposition","attachment;filename=" + filename);
                byte[] car=new byte[1024];
                int L=0;
                while((L=in.read(car))!=-1){
                   out.write(car, 0,L);
                }
                if(out!=null){
                   out.flush();
                   out.close();
                }
                if(in!=null){
                   in.close();
                }
            } catch (IOException e) {
                logger.error("the download file error :" + e.getMessage());
                throw new ErrorException("200003", errorMsgUtils.errorMsg("","200003"));
            }
        }
    }

最后是ZipUtils类内容

public class ZipUtils {
    
      private ZipUtils(){
        }
        
        public static void doCompress(String srcFile, String zipFile) throws IOException {
            doCompress(new File(srcFile), new File(zipFile));
        }
        
        /**
         * 文件压缩
         * @param srcFile 目录或者单个文件
         * @param zipFile 压缩后的ZIP文件
         */
        public static void doCompress(File srcFile, File zipFile) throws IOException {
            ZipOutputStream out = null;
            try {
                out = new ZipOutputStream(new FileOutputStream(zipFile));
                doCompress(srcFile, out);
            } catch (Exception e) {
                throw e;
            } finally {
                out.close();//记得关闭资源
            }
        }
        
        public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
            doCompress(new File(filelName), out);
        }
        
        public static void doCompress(File file, ZipOutputStream out) throws IOException{
            doCompress(file, out, "");
        }
        
        public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
            if ( inFile.isDirectory() ) {
                File[] files = inFile.listFiles();
                if (files!=null && files.length>0) {
                    for (File file : files) {
                        String name = inFile.getName();
                        if (!"".equals(dir)) {
                            name = dir + "/" + name;
                        }
                        ZipUtils.doCompress(file, out, name);
                    }
                }
            } else {
                 ZipUtils.doZip(inFile, out, dir);
            }
        }
        
        public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
            String entryName = null;
            if (!"".equals(dir)) {
                entryName = dir + "/" + inFile.getName();
            } else {
                entryName = inFile.getName();
            }
            ZipEntry entry = new ZipEntry(entryName);
            out.putNextEntry(entry);
            
            int len = 0 ;
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(inFile);
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.closeEntry();
            fis.close();
        }
        
        //
        public static void doZip(InputStream inputStream, ZipOutputStream out, String entryName) throws IOException {
//          String entryName = null;
//          if (!"".equals(dir)) {
//              entryName = dir + "/" + inFile.getName();
//          } else {
//              entryName = inFile.getName();
//          }
            ZipEntry entry = new ZipEntry(entryName);
            out.putNextEntry(entry);
            
            int len = 0 ;
            byte[] buffer = new byte[1024];
//          FileInputStream fis = new FileInputStream(inFile);
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.closeEntry();
            inputStream.close();
        }
        
        public static void main(String[] args) throws IOException {
            doCompress("G:/test/", "G:/java.zip");
        }
        
}

转载于:https://www.cnblogs.com/ylzhang/p/8515139.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值