1
0

DownloadUtils.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package com.siwei.apply.utils;
  2. import javax.servlet.http.HttpServletResponse;
  3. import java.io.File;
  4. import java.nio.file.Files;
  5. import java.util.ArrayList;
  6. import java.util.zip.ZipOutputStream;
  7. /**
  8. * 下载工具类
  9. */
  10. public class DownloadUtils {
  11. /**
  12. * 将所有文件打包成zip并下载
  13. *
  14. * @param response
  15. * @param files 文件地址集合
  16. * @param filename zip的文件名
  17. */
  18. public static void DownloadZip(HttpServletResponse response, ArrayList<String> files, String filename) {
  19. ZipOutputStream zipOutputStream = null;
  20. try {
  21. response.setHeader("Content-Disposition", "attachment;filename=" + new String((filename + ".zip").getBytes("UTF-8"), "ISO-8859-1")); // 需要编z码否则中文乱码
  22. response.setContentType("application/zip;charset=utf-8");
  23. response.setCharacterEncoding("UTF-8");
  24. // 直接返回zip输出流不生成临时文件。
  25. zipOutputStream = new ZipOutputStream(response.getOutputStream());
  26. for (String path : files) {
  27. File file = new File(path);
  28. if (file.exists()) {
  29. byte[] readAllBytes = Files.readAllBytes(file.toPath());
  30. org.apache.tools.zip.ZipEntry zipEntry = new org.apache.tools.zip.ZipEntry(file.getName());
  31. zipOutputStream.putNextEntry(zipEntry);
  32. zipOutputStream.write(readAllBytes);
  33. }
  34. }
  35. zipOutputStream.close();
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. } finally {
  39. try {
  40. zipOutputStream.close();
  41. } catch (Exception e) {
  42. }
  43. }
  44. }
  45. }