gpt4 book ai didi

java - 在 Java 中从 inputStream 压缩多个对象

转载 作者:行者123 更新时间:2023-11-30 09:11:08 33 4
gpt4 key购买 nike

我有一个网络应用程序,允许用户选择图像然后下载它们。对于单个图像,我使用 HTML5 的 anchor 下载,效果非常好。现在我需要允许他们选择多个图像,并将它们下载为 .zip 文件。我正在使用 api 将每个图像作为 InputStream 并返回 Jersey Response。

我是压缩新手,我对使用 InputStream 进行压缩的工作方式有点困惑。

对于单张图片,它是这样工作的:

try {
InputStream imageInputStream = ImageStore.getImage(imageId);

if (imageInputStream == null) {
XLog.warnf("Unable to find image [%s].", imageId);
return Response.status(HttpURLConnection.HTTP_GONE).build();
}

Response.ResponseBuilder response = Response.ok(imageInputStream);
response.header("Content-Type", imageType.mimeType());
response.header("Content-Disposition", "filename=image.jpg");

return response.build();
}

虽然不多,但这是我目前拥有的用于多张图片

的java
public Response zipAndDownload(List<UUID> imageIds) {
try {
// TODO: instantiate zip file?

for (UUID imageId : imageIds) {
InputStream imageInputStream = ImageStore.getImage(imageId);
// TODO: add image to zip file (ZipEntry?)
}

// TODO: return zip file
}
...
}

我只是不知道如何处理多个 InputStreams,看来我不应该有多个,对吧?

最佳答案

每个图像一个 InputStream 就可以了。要压缩文件,您需要为它们创建一个 .zip 文件并获取一个 ZipOutputStream 来写入它:

File zipFile = new File("/path/to/your/zipFile.zip");
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

对于每个图像,创建一个新的 ZipEntry,将其添加到 ZipOutputSteam,然后将字节从图像的 InputStream 复制到 ZipOutputStream:

ZipEntry ze = new ZipEntry("PrettyPicture1.jpg");
zos.putNextEntry(ze);
byte[] bytes = new byte[1024];
int count = imageInputStream.read(bytes);
while (count > -1)
{
zos.write(bytes, 0, count);
count = imageInputStream.read(bytes);
}
imageInputStream.close();
zos.closeEntry();

添加所有条目后,关闭 ZipOutputStream:

zos.close();

现在您的 zipFile 指向一个充满图片的 zip 文件,您可以随意使用它。您可以像处理单个图像一样返回它:

BufferedInputStream zipFileInputStream = new BufferedInputStream(new FileInputStream(zipFile));
Response.ResponseBuilder response = Response.ok(zipFileInputStream);

但内容类型和配置不同:

response.header("Content-Type", MediaType.APPLICATION_OCTET_STREAM_TYPE);
response.header("Content-Disposition", "attachment; filename=zipFile.zip");

注意:您可以使用Guava's ByteStreams helper 中的复制 方法复制流而不是手动复制字节。只需用以下行替换 while 循环和它之前的两行:

ByteStreams.copy(imageInputStream, zos);

关于java - 在 Java 中从 inputStream 压缩多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260151/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com