Springboot将多个图片导出成zip压缩包

Springboot将多个图片导出成zip压缩包

将多个图片导出成zip压缩包

java 复制代码
/**
     * 判断时间差是否超过6小时
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return
     */
    public static boolean isWithin6Hours(String startTime, String endTime) {
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 将字符串转换为 LocalDateTime
        LocalDateTime startDateTime = LocalDateTime.parse(startTime,formatter);
        LocalDateTime endDateTime = LocalDateTime.parse(endTime,formatter);

        // 检查两个时间之间的时间差
        long hoursDifference = ChronoUnit.SECONDS.between(startDateTime, endDateTime);

        // 如果小时差小于等于6小时,则符合条件
        return hoursDifference <= 6 * 60 * 60;
    }

    /**
     * 批量下载上传的图片
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    public void batchDownloadUploadPhoto(String startTime, String endTime,String fieldId,String unitTypeId,Integer unitNo,Integer termAddr, HttpServletResponse response, HttpServletRequest request) {

        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
            throw new DataValidateErrorException("请先传递时间在批量导出!");
        }

        if (!startTime.contains(":") || !endTime.contains(":")) {
            throw new DataValidateErrorException("请传递时分秒");
        }

        //相隔时间不得超过6小时
        if(!isWithin6Hours(startTime,endTime)){
            //大于6小时,抛出异常
            throw new DataValidateErrorException("导出的时间范围不得超过6小时!");
        }


        //查询导出图片url
        List<ChuteImageAddress> addressList = chuteImageAddressService.selectUploadPhoto(startTime, endTime, fieldId, unitTypeId, unitNo, termAddr);

        //没有数据时,抛出异常
        if(CollectionUtils.isEmpty(addressList)){
            throw new DataValidateErrorException("无数据导出!");
        }


        DownloadByteArray downloadByteArray = new DownloadByteArray();

        // 创建临时文件
        File zipFile = null;
        FileInputStream fis = null;
        BufferedInputStream buff = null;
        ZipOutputStream zos = null;
        CheckedOutputStream cos = null;
        FileOutputStream fot = null;
        ServletOutputStream os = null;
        try {
            //临时文件名称
            zipFile = File.createTempFile("" + System.currentTimeMillis(), ".zip");

            fot = new FileOutputStream(zipFile);
            // 为任何OutputStream产生校验,第一个参数是制定产生校验和的输出流,第二个参数是指定Checksum的类型 (Adler32(较快)和CRC32两种)

            cos = new CheckedOutputStream(fot, new Adler32());
            // 用于将数据压缩成Zip文件格式

            zos = new ZipOutputStream(cos);

            String[] files = new String[addressList.size()];
            List<String> list = addressList.stream().map(ChuteImageAddress::getImgUrl).collect(Collectors.toList());
            list.toArray(files);

            for (int i = 0; i < files.length; i++) {
                String file = files[i];
                zos.putNextEntry(new ZipEntry(addressList.get(i).getImgName()));
                StorePath storePath = StorePath.praseFromUrl(file);
                byte[] fileBytes = client.downloadFile(storePath.getGroup(), storePath.getPath(), downloadByteArray);
                zos.write(fileBytes);
            }

            os = response.getOutputStream();
            //下载文件,使用spring框架中的FileCopyUtils工具
            response.setCharacterEncoding("GB2312");
            response.setContentType(request.getSession().getServletContext().getMimeType(UUIDUtil.create()));
            //设置响应头,attachment表示以附件的形式下载,inline表示在线打开
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("批量下载.zip", "UTF-8"));
            fis = new FileInputStream(zipFile);
            buff = new BufferedInputStream(fis);
            FileCopyUtils.copy(buff, os);
        } catch (Exception e) {
            log.error("【批量下载图片出现异常】异常原因" + e.getMessage());
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (fot != null) {
                try {
                    fot.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (buff != null) {
                try {
                    buff.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }


相关推荐
coderSong256821 分钟前
Java高级 |【实验八】springboot 使用Websocket
java·spring boot·后端·websocket
老胖闲聊44 分钟前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1181 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
Mr_Air_Boy1 小时前
SpringBoot使用dynamic配置多数据源时使用@Transactional事务在非primary的数据源上遇到的问题
java·spring boot·后端
曹勖之1 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
lyaihao2 小时前
使用python实现奔跑的线条效果
python·绘图
咖啡啡不加糖2 小时前
Redis大key产生、排查与优化实践
java·数据库·redis·后端·缓存
大鸡腿同学3 小时前
纳瓦尔宝典
后端
ai大师3 小时前
(附代码及图示)Multi-Query 多查询策略详解
python·langchain·中转api·apikey·中转apikey·免费apikey·claude4
懒虫虫~3 小时前
基于SpringBoot解决RabbitMQ消息丢失问题
spring boot·rabbitmq