java 将多张图片文件压缩zip下载

1、controller  前端把图片文件的id用逗号隔开拼起来传给后端。

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
60
61
62
63
/**
 * 下载选中资源
 *
 * @param response
 * @return: void
 */
@GetMapping("downloadDataZip")
public void downloadDataZip(String signs, HttpServletResponse response) {
    String[] strSigns = signs.split(",");
    List<Long> ids = new ArrayList<>();
    for(String sign : strSigns){
        Long tmpId = Security.decodeSignQuiet(sign);
        ids.add(tmpId);
    }
 
    List<StoreImgModel> modelList = storeImgService.listByIds(ids);
    Map<String, String> srcFiles = new HashMap<>();
    for(StoreImgModel imgModel : modelList){
        srcFiles.put(imgModel.getName(), imgModel.getImgUrl());
    }
 
    String title ="下载选中图片.zip";
    File filePath = new File(FileUtil.getTemplatePath() + File.separator + title);
    FileUtil.zipFiles(srcFiles, filePath);
    String filename = System.currentTimeMillis()+"_"+title;
    //设置文件路径
    if (filePath.exists()) {
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
            byte[] buffer = new byte[4096];
            fis = new FileInputStream(filePath);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                    // 删除临时文件
                    filePath.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  2、创建一个文件处理工具类  FileUtil.java 

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package common.util;
 
 
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class FileUtil {
 
    /**
     * 多图片压缩zip
     *
     * @param srcFiles 图片名称
     * @param zipFile  文件路径
     */
    public static void zipFiles(Map<String, String> srcFiles, File zipFile) {
 
        // 判断压缩后的文件存在不,不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream ;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream ;
        // 创建 FileInputStream 对象
        BufferedInputStream bis = null;
 
        InputStream inputStream = null;
 
        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry ;
            // 遍历源文件数组
            for (String file : srcFiles.keySet()) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                String fileName = file;
                URL url = new URL(srcFiles.get(file));
                inputStream = url.openStream();
                // 文件后缀名称
                // 实例化 ZipEntry 对象,源文件数组中的当前文件
                zipEntry = new ZipEntry(fileName);
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[4096];
                while ((len = inputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
 
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
 
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 获取类路径
     * return 绝对路径地址
     */
    public static String getTemplatePath() {
        String realPath = FileUtil.class.getClassLoader().getResource("").getFile();
        File file = new File(realPath);
        realPath = file.getAbsolutePath();
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return realPath;
    }
 
}

  3、前端请求,直接用window.location.href

1
2
3
4
5
6
7
8
9
10
11
batchDownload: function (){
                let data = table.checkStatus('ImgTableId').data;
                let signs = "";
                data.forEach((item, index)=>{
                    signs += item.sign + ",";
                });
                if (signs && signs.endsWith(",")){
                    signs = signs.substr(0, signs.length -1);
                }
                window.location.href = "${serverBaseUrl}/downloadDataZip?signs="+signs;
            }

  

参考:https://blog.csdn.net/zouliping123456/article/details/115211866

posted @   war3_xiaofeng  阅读(619)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言
点击右上角即可分享
微信分享提示