利用压缩包的形式进行批量下载


    1. /**
    2. * 将磁盘的多个文件打包成压缩包并输出流下载
    3. *
    4. * @param pathList
    5. * @param response
    6. */
    7. public void zipDirFileToFile(List<Map<String, String>> pathList, HttpServletResponse response, String taskName) {
    8. try {
    9. // 设置response参数并且获取ServletOutputStream
    10. ZipArchiveOutputStream zous = getServletOutputStream(response, taskName);
    11. for (Map<String, String> map : pathList) {
    12. String fileName = map.get("outputName");
    13. File file = new File(map.get("localFileName"));
    14. InputStream inputStream = new FileInputStream(file);
    15. setByteArrayOutputStream(fileName, inputStream, zous);
    16. }
    17. zous.close();
    18. } catch (Exception e) {
    19. e.printStackTrace();
    20. }
    21. }
    22. public ZipArchiveOutputStream getServletOutputStream(HttpServletResponse response, String taskName) throws Exception {
    23. //输出压缩文件名年月日时分秒
    24. String outputFileName = taskName + ".zip";
    25. Log.info("压缩文件名:" + outputFileName);
    26. response.reset();
    27. response.setHeader("Content-Type", "application/octet-stream");
    28. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(outputFileName, "UTF-8"));
    29. response.setHeader("Pragma", "no-cache");
    30. response.setHeader("Cache-Control", "no-cache");
    31. ServletOutputStream out = response.getOutputStream();
    32. ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
    33. zous.setUseZip64(Zip64Mode.AsNeeded);
    34. return zous;
    35. }
    36. public void setByteArrayOutputStream(String fileName, InputStream inputStream, ZipArchiveOutputStream zous) throws Exception {
    37. ByteArrayOutputStream baos = new ByteArrayOutputStream();
    38. byte[] buffer = new byte[5120];
    39. int len;
    40. while ((len = inputStream.read(buffer)) != -1) {
    41. baos.write(buffer, 0, len);
    42. }
    43. baos.flush();
    44. byte[] bytes = baos.toByteArray();
    45. //设置文件名
    46. ArchiveEntry entry = new ZipArchiveEntry(fileName);
    47. zous.putArchiveEntry(entry);
    48. zous.write(bytes);
    49. zous.closeArchiveEntry();
    50. baos.close();
    51. inputStream.close();
    52. }