将指定目录图片打成压缩包下载

直接贴代码:

import org.springframework.core.io.InputStreamResource;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class ImageController {

    public ByteArrayOutputStream compressImages(List<String> imagePaths) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ZipOutputStream zos = new ZipOutputStream(baos)) {
            for (String imagePath : imagePaths) {
                Path path = Paths.get(imagePath);
                if (Files.exists(path) && Files.isRegularFile(path)) {
                    try {
                        ZipEntry zipEntry = new ZipEntry(path.getFileName().toString());
                        zos.putNextEntry(zipEntry);
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("File does not exist: " + imagePath);
                }
            }
        }
        return baos;
    }


    @GetMapping("/download-images")
    public ResponseEntity<InputStreamResource> downloadImages(@RequestParam List<String> directories) {
        try {
            ByteArrayOutputStream baos = compressImages(directories);

            // 将 ByteArrayOutputStream 转换为 ByteArrayInputStream
            ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=images.zip");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/zip");

            // 返回 ResponseEntity,包含 InputStreamResource 和响应头
            return new ResponseEntity<>(new InputStreamResource(inputStream), headers, HttpStatus.OK);

        } catch (IOException e) {
            // 记录错误日志并返回服务器内部错误状态
            e.printStackTrace(); // 考虑使用日志记录框架
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值