在Google App Engine (Java)中创建ZIP归档文件

3
我正在尝试克隆一个模板(带有嵌套子文件夹的文件夹),替换几个文件,将其压缩并提供给用户。由于没有本地存储,因此在App Engine中是否可以完成此操作?
***更新*** 困难在于在内存中构建目录结构,然后压缩它。 幸运的是,在stackoverflow上我找到了这篇文章: java.util.zip - 重新创建目录结构 其余部分很简单。
谢谢大家。
1个回答

5

可以实现。

按照您的理解,您想要提供一个zip文件。在将zip文件作为servlet响应发送给客户端之前,您不需要事先保存它。您可以直接将生成/即时生成的zip文件发送到客户端。(请注意,AppEngine会缓存响应并在准备好响应时将其作为整个响应发送,但这与本题无关。)

将内容类型设置为application/zip,并通过将servlet的输出流作为构造函数参数传递给ZipOutputStream来创建和发送响应zip文件。

以下是使用HttpServlet的示例:

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
        ServletException, IOException {
    // Process parameters and do other stuff you need

    resp.setContentType("application/zip");
    // Indicate that a file is being sent back:
    resp.setHeader("Content-Disposition", "attachment;filename=template.zip");

    try (ZipOutputStream out = new ZipOutputStream(resp.getOutputStream())) {
        // Here go through your template / folders / files, optionally 
        // filter them or replace them with the content you want to include

        // Example adding a file to the output zip file:
        ZipEntry e = new ZipEntry("some/folder/image.png");
        // Configure the zip entry, the properties of the file
        e.setSize(1234);
        e.setTime(System.currentTimeMillis());
        // etc.
        out.putNextEntry(e);
        // And the content of the file:
        out.write(new byte[1234]);
        out.closeEntry();

        // To add another file to the output zip,
        // call putNextEntry() again with the entry,
        // write its content with the write() method and close with closeEntry().

        out.finish();
    } catch (Exception e) {
        // Handle the exception
    }
}

注意:根据您的情况,您可能需要禁用响应zip文件的缓存。如果您想通过代理和浏览器禁用结果的缓存,请在启动ZipOutputStream之前添加以下行:

resp.setHeader("Cache-Control", "no-cache"); // For HTTP 1.1
resp.setHeader("Pragma", "no-cache"); // For HTTP 1.0
resp.setDateHeader("Expires", 0); // For proxies

当压缩文件大小超过30M的限制时,我该怎么办? - RCB
@RCB 首先,您必须将其保存到Google Cloud Storage或Blobstore中,并从那里提供服务。或者将其拆分为多个文件。或使用Compute Engine来提供服务。 - icza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接