直接贴代码:
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();
}
}
}