多个图片合并为一个压缩包下载

之前项目上遇到上传多个图片,一个下载按钮可以下载所有的图片,本来想多次触发下载请求,但是失败了,于是就转为合并为一个压缩包下载,下面是代码

 List<Files> filesList =(List<Files>)request.getAttribute("files");

 String basepath = WebUtil.formatPath(pageContext.getServletContext().getRealPath("/"));

 String fileNameToClient=(String) request.getAttribute("downloadName")+"_"+ DateUtil.format(new Date(), DateUtil.yyyyMMddHHmmss);

 response.setContentType("application/zip");

 response.setHeader("Content-Disposition", "attachment;filename=\"" + fileNameToClient + ".rar\"");

 ZipOutputStream zipout = new ZipOutputStream(response.getOutputStream());

 zipout.setLevel(1);

 BufferedOutputStream bos = new BufferedOutputStream(zipout);

 for (int i = 0; i < filesList.size(); i++) {

   Files files = filesList.get(i);

   String path = files.getFileWeburl(basepath, "/web/resource");

   File f = new File(path);

   if (f.canRead()) {

       zipout.putNextEntry(new ZipEntry(files.getSrcfilename()));

       BufferedInputStream fr = new BufferedInputStream(new FileInputStream(f));

       byte buffer[] = new byte[1024];

        int b;

       while ((b = fr.read(buffer,0,buffer.length)) != -1) zipout.write(buffer,0,b);

        fr.close();

        bos.flush();
     }
  }
  bos.close();

    原文作者:今天吃什么菜
    原文地址: https://blog.csdn.net/weixin_42085125/article/details/123903582
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞