下面一段代码给大家分享JavaWeb实现压缩多个文件并下载功能,具体代码如下所示:

//文件名称
    String[] names={"one.jpg","two.jpg","three.jpg","four.jpg"};
    //四个文件流
    FileInputStream input1 = new FileInputStream(new File("文件路径"));
    FileInputStream input2 = new FileInputStream(new File("文件路径"));
    FileInputStream input3 = new FileInputStream(new File("文件路径"));
    FileInputStream input4 = new FileInputStream(new File("文件路径"));
    FileInputStream[] inputs={input1,input2,input3,input4};
    //ZIP打包图片
    File zipFile = new File("压缩文件存放路径");
    byte[] buf = new byte[1024];
    int len;
    ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(zipFile));
    for (int i = 0; i < inputs.length; i++) {
      FileInputStream in =inputs[i];
      zout.putNextEntry(new ZipEntry(names[i]));
      while ((len = in.read(buf)) > 0) {
        zout.write(buf, 0, len);
      }
      zout.closeEntry();
      in.close();
    }
    zout.close();
    //下载图片
    FileInputStream zipInput =new FileInputStream(zipFile);
    OutputStream out = response.getOutputStream();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=images.zip");
    while ((len=zipInput.read(buf))!= -1){
      out.write(buf,0,len);
    }
    zipInput.close();
    out.flush();
    out.close();
    //删除压缩包
    zipFile.delete();

总结

以上所述是小编给大家介绍的JavaWeb实现压缩多个文件并下载实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

02-09 06:22