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


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

        /**
         * 下载选中资源
         *
         * @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 

    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

    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

  • 相关阅读:
    错误 1 类,结构或接口成员声明中的标记"="无效
    转asp.net中的App_GlobalResources和App_LocalResources使用
    input type=file 上传文件样式美化(转载)
    Postman Post请求上传文件
    vuex 、store、state (转载)
    ES5、ES2015、ECMAScript6(转载)
    axios 用法简介(转载)
    js中const,var,let区别(转载)
    C#开发微信公众平台-就这么简单(附Demo)转载
    什么是 Native、Web App、Hybrid、React Native 和 Weex?(转载)
  • 原文地址:https://www.cnblogs.com/leeke/p/15608858.html
Copyright © 2020-2023  润新知