一、详细代码

1.Controller层

代码如下(示例):

    @PostMapping("/download")
    public GeneralResult downloadFilesTest(HttpServletRequest request,
                                           HttpServletResponse response){
        return scriptService.downloadFilesTest(request,response);
    }

2.Service层

   public void downloadFilesTest(HttpServletRequest request, HttpServletResponse response){
   String filePath = "D:/test" //test为D盘下的文件夹
   File file = new File(filePath);
   //创建输出流
   OutPutStream out = null;
   ZipOutputStream zos = null;
   try{
   out = response.getOutputStream();
   zos = new ZipOutputStream(out);
   compress(file,zos,file.getName()); //压缩文件方法
   //刷新流和关闭流,注意流的关闭顺序,否则压缩文件出来会损坏
   zipOutputStream.flush();
   out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
   	 }
   }

 private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {
 	byte[] buf = new byte[1024];
 	if(sourceFile.isFile()){ //判断是否为文件
 	// 压缩单个文件,压缩后文件名为当前文件名
       zos.putNextEntry(new ZipEntry(name));
        // copy文件到zip输出流中
        int len;
        FileInputStream in = new FileInputStream(sourceFile);
        while ((len = in.read(buf)) > 0) {
            zos.write(buf, 0, len);
        }
        zos.closeEntry();
        in.close();
      }else { //路径文件为文件夹,用递归的方法压缩文件夹下的文件
         File[] listFiles = sourceFile.listFiles();
          if (listFiles == null || listFiles.length == 0) {
              // 空文件夹的处理
          } else {
              // 递归压缩文件夹下的文件
              for (File file : listFiles) {
                  compress(file, zos, name + "/" + file.getName());
              }
          }
      }
 }
 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐