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

文章讲述了如何在Springboot应用中,通过时间范围批量下载上传的图片,然后将这些图片压缩为zip文件并返回给用户。方法涉及时间验证和文件操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

/**
     * 判断时间差是否超过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();
                }

            }
        }
    }

在这里插入图片描述
在这里插入图片描述

### Spring Boot 实现 ZIP 文件导出的功能 在 Spring Boot 中实现 ZIP 文件的导出功能可以通过创建一个控制器来处理 HTTP 请求,并将多个文件打包 ZIP 格式返回给客户端。以下是完整的解决方案: #### 控制器代码示例 下面是一个基于 Spring Boot 的控制器示例,用于导出 ZIP 文件。 ```java import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @RestController public class FileExportController { @GetMapping("/export-zip") public ResponseEntity<byte[]> exportZip() { try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) { // 添加第一个文件到 ZIP 压缩包中 String content1 = "This is the content of file1.txt"; addFileToZip(zipOutputStream, "file1.txt", content1); // 添加第二个文件到 ZIP 压缩包中 String content2 = "This is the content of file2.txt"; addFileToZip(zipOutputStream, "file2.txt", content2); byte[] zipBytes = byteArrayOutputStream.toByteArray(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=files.zip"); return new ResponseEntity<>(zipBytes, headers, HttpStatus.OK); } catch (IOException e) { throw new RuntimeException("Error while creating zip archive", e); // 异常处理逻辑[^1] } } private void addFileToZip(ZipOutputStream zipStream, String fileName, String content) throws IOException { ZipEntry entry = new ZipEntry(fileName); zipStream.putNextEntry(entry); zipStream.write(content.getBytes()); zipStream.closeEntry(); } } ``` 上述代码定义了一个 RESTful API `/export-zip`,当访问该接口时会生并返回一个包含两个文本文件 (`file1.txt`, `file2.txt`) 的 ZIP 文件。 #### 测试类代码示例 为了验证此功能是否正常工作,可以编写如下测试代码: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(FileExportController.class) public class FileExportControllerTest { @Autowired private MockMvc mockMvc; @Test public void testExportZip() throws Exception { this.mockMvc.perform(get("/export-zip")) .andExpect(status().isOk()); // 验证状态码为 200 OK[^2] } } ``` 这段代码展示了如何使用 JUnit 和 Spring MVC Test 工具对控制器方法进行单元测试。 --- ### 注意事项 - 如果需要动态读取磁盘上的实际文件而不是字符串内容,则应调整 `addFileToZip` 方法以支持流操作。 - 对于较大的文件集合或高并发场景,建议优化内存管理策略,例如采用分块写入的方式减少内存占用。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

VX_codejams

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值