java - 在 Google App Engine (Java) 中创建 ZIP 文件

标签 java google-app-engine zip archive

<分区>

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

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

其余的都是微不足道的。

谢谢大家,

最佳答案

是的,这是可以做到的。

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

将内容类型设置为application/zip,您可以通过实例化ZipOutputStream 将servlet 的输出流作为构造函数参数传递来创建和发送响应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

关于java - 在 Google App Engine (Java) 中创建 ZIP 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24603201/

相关文章:

google-app-engine - 将 App Engine java 图像 api 与 eclipse + 开发服务器一起使用?

xml - 压缩文件夹最终会出错,具体取决于1个文件

PHP 从 zip 文件目录中读取文本文件

java - 在 Hibernate 5.3 上获取带有 id 的实体列表

java - 如何将位图背景替换为特定颜色

java - 神经网络为每个输入返回相同的输出

java - 数据存储查询过期的速度有多快?

java SocketException : Connection reset

google-app-engine - App 引擎应用程序和 Datastore 的权限问题

python - 允许用户下载在 AWS 上生成的 zip 文件