通过浏览器批量下载文件到zip压缩包

     /**
      * 批量下载证件照、文件
      *
      * @return
      */
     @GetMapping("/downLoadImgs")
     @Transactional
     public void downLoadImgs(HttpServletRequest request,@RequestParam(name = "ids", required = true) String ids, HttpServletResponse response) {
         //1.拿到对应图片地址的url数组
         String[] array = ids.split(",");
         ArrayList<String> idList = new ArrayList<>(Arrays.asList(array));
         //根据ids查询出所有的档案
         List<XzFile> xzFiles = xzFileService.selectBatchIds(idList);
         ArrayList<String> urls = new ArrayList<>();
         for (XzFile xzFile : xzFiles) {
             //todo 在图片路径加上前缀
             urls.add("http:*****"+xzFile.getIdPhoto());
         }
         String[] files = new String[urls.size()];
         urls.toArray(files);
         //2.开始批量下载功能
         try {
//            String nowTimeString = TimeUtils.getNowTimeString();
             String downloadFilename = "证件照" + ".zip";//文件的名称
             downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");//转换中文否则可能会产生乱码
             response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
             response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);// 设置在下载框默认显示的文件名
             ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
             for (int i = 0; i < files.length; i++) {
                 URL url = new URL(files[i]);
                 //拿到文件名
                 String spath=xzFiles.get(i).getIdPhoto();
                 int pos = spath.lastIndexOf('\');
                 String sfilename = spath.substring(pos + 1);//带扩展名
                 pos = sfilename.lastIndexOf('.');
                 String sfilenameEx = sfilename.substring(0,pos);//不带扩展名
                 //设置文件名
                 zos.putNextEntry(new ZipEntry(sfilenameEx + ".jpg"));
                 InputStream fis = url.openConnection().getInputStream();
                 byte[] buffer = new byte[1024];
                 int r = 0;
                 while ((r = fis.read(buffer)) != -1) {
                     zos.write(buffer, 0, r);
                 }
                 fis.close();
             }
             zos.flush();
             zos.close();
         } catch (Exception e) {
             return ;
         }

     }
原文地址:https://www.cnblogs.com/zagwk/p/13972313.html