在Spring Boot中下载许多图像并压缩成zip文件的方法



我想将存储在数据库中的blob图像转换为jpeg文件,然后以zip文件的形式下载。

这是目前为止的实现。

public void downloadImages(HttpServletResponse response) throws IOException {
List<ScreenUserEntity> users = screenUserRepository.findAll()
.stream().filter( user -> user.getImage() != null && user.getImage().length > 0).collect(Collectors.toList());
String filename = "Image.jpeg";
response.setContentType("image/jpeg");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="" + filename + """);
byte[] decodedBytes = users.get(0).getImage();
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
BufferedImage image = ImageIO.read(bis);
File outputFile = new File("output.png");
ImageIO.write(image, "png", outputFile);
}

是否有办法将文件/图像/zip文件添加到响应中?

谢谢你的帮助/

List<ScreenUserEntity> users = screenUserRepository.findAll()
.stream()
.filter( user -> user.getImage() != null && user.getImage().length > 0)
.collect(Collectors.toList());

将它们全部加载到内存中。我想你不会想这么做的;如果有几个用户,您的服务器就会崩溃。最好的情况是,它杀死这个占用过多内存的响应处理程序。

是否有办法将文件/图像/zip文件添加到响应中?

肯定!我对原始HttpServletResponse的使用有点困惑;这里的问题稍微复杂了一点:HTTP作为标准要求你要么[a]在发送之前发送你所发送的内容的大小,要么[B]使用分块传输编码。

如果你只是抓取一个输出流并开始发送,那么默认情况下java中的大多数servlet引擎会首先将该数据存储到内存中(这很烦人;您有太多东西要发送),或者发送到临时文件(这很不幸),并且在您完全完成之前,不要实际通过网络发送任何字节。你不会想要那样的。这取决于你的实现,参见这个答案。这是你可能想要调查的事情,例如使用你最喜欢的浏览器的开发工具。

无论如何,一旦你排序好了,这就是你如何"流"一个zip文件的方法(实时生成数据,以块的形式发送,不需要大量的内存,同时避免生成临时文件):

try (OutputStream raw = response.getOutputStream();
ZipOutputStream zip = new ZipOutputStream(raw)) {
for (ScreenUserEntity user : screenUserRepo.findAll()) {
byte[] img = user.getImage();
if (img == null || img.length == 0) continue;
zip.putNextEntry(new ZipEntry(user.getName() + ".jpg"));
zip.write(img);
}
}

最新更新