| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- package com.siwei.apply.utils;
- import javax.servlet.http.HttpServletResponse;
- import java.io.File;
- import java.nio.file.Files;
- import java.util.ArrayList;
- import java.util.zip.ZipOutputStream;
- /**
- * 下载工具类
- */
- public class DownloadUtils {
- /**
- * 将所有文件打包成zip并下载
- *
- * @param response
- * @param files 文件地址集合
- * @param filename zip的文件名
- */
- public static void DownloadZip(HttpServletResponse response, ArrayList<String> files, String filename) {
- ZipOutputStream zipOutputStream = null;
- try {
- response.setHeader("Content-Disposition", "attachment;filename=" + new String((filename + ".zip").getBytes("UTF-8"), "ISO-8859-1")); // 需要编z码否则中文乱码
- response.setContentType("application/zip;charset=utf-8");
- response.setCharacterEncoding("UTF-8");
- // 直接返回zip输出流不生成临时文件。
- zipOutputStream = new ZipOutputStream(response.getOutputStream());
- for (String path : files) {
- File file = new File(path);
- if (file.exists()) {
- byte[] readAllBytes = Files.readAllBytes(file.toPath());
- org.apache.tools.zip.ZipEntry zipEntry = new org.apache.tools.zip.ZipEntry(file.getName());
- zipOutputStream.putNextEntry(zipEntry);
- zipOutputStream.write(readAllBytes);
- }
- }
- zipOutputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- zipOutputStream.close();
- } catch (Exception e) {
- }
- }
- }
- }
|