我正在尝试克隆模板(带有嵌套子文件夹的文件夹),替换几个文件,将其压缩并提供给用户。这可以在App Engine中完成,因为没有本地存储吗?
***更新**** 难以在内存中构建目录结构然后将其压缩。 幸运的是我在stackoverflow上发现了这篇文章: java.util.zip - Recreating directory structure
其余的都是微不足道的。
谢谢大家,
答案 0 :(得分:3)
是的,这可以做到。
据我了解,您想要提供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