ZQN
2024-08-14 5cbb2e7fc3d81ac895548179a7be9a65fa726c6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.project.common.utils.zip;
 
import cn.hutool.core.util.ZipUtil;
import com.project.common.config.ProjectConfig;
import com.project.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
 
@Component
@Slf4j
public class ZipUtils {
 
    // 本地资源路径
    private static String localPath = ProjectConfig.getQrcodePath();
 
    /**
     * 下载多个文件转zip压缩包
     *
     * @param list 图片数组
     * @param response  响应
     */
    public static void downloadToZip(List<String> list, List<String> names, HttpServletResponse response)
    {
        int i = 0;
        //如果有附件 进行zip处理
        if (StringUtils.isNotEmpty(list)) {
            try {
                //被压缩文件流集合
                InputStream[] srcFiles = new InputStream[list.size()];
                //被压缩文件名称
                String[] srcFileNames = new String[list.size()];
                for (String path : list) {
                    //以下代码为获取图片inputStream
                    String s = path.substring(path.lastIndexOf("/"));
                    InputStream ins = Files.newInputStream(Paths.get(localPath + s));
                    //塞入流数组中
                    srcFiles[i] = ins;
                    srcFileNames[i] = names.get(list.indexOf(path))+".png";
                    i++;
                }
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下载.zip", "UTF-8"));
                //多个文件压缩成压缩包返回
                ZipUtil.zip(response.getOutputStream(), srcFileNames, srcFiles);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
}