在 Google App Engine (Java) 中创建 ZIP 档案

Jav*_*ead 3 java zip google-app-engine archive

我正在尝试克隆一个模板(带有嵌套子文件夹的文件夹),替换一些文件,将其压缩并提供给用户。由于没有本地存储,这可以在 App Engine 中完成吗?

*** 更新**** 在内存中建立一个目录结构,然后将其压缩是很困难的。幸运的是我在 stackoverflow 上找到了这篇文章: java.util.zip - Recreating directory structure

其余的都是微不足道的。

谢谢大家,

icz*_*cza 5

是的,这是可以做到的。

据我了解,您想提供一个 zip 文件。在将 zip 文件作为 servlet 的响应发送到客户端之前,您不需要保存它。您可以在生成/即时生成 zip 文件时直接将其发送到客户端。(请注意,AppEngine 将缓存响应并在您的响应准备好时将其作为整体发送,但这在这里无关紧要。)

将内容类型设置为application/zip,您可以通过实例化ZipOutputStreamservlet 的输出流作为构造函数参数来创建和发送响应 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
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:您可能想要禁用响应 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
Run Code Online (Sandbox Code Playgroud)