您好,我正在尝试编写一个可以下载多个文件的 Play Framework 服务。我即时创建了多个文件的 zip,但我不确定如何在 Play Framework 中将其作为响应发送,我将展示我到目前为止所做的事情。
public Result download() {
String[] items = request().queryString().get("items[]");
String toFilename = request().getQueryString("toFilename");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) {
for (String item : items) {
Path path = Paths.get(REPOSITORY_BASE_PATH, item);
if (Files.exists(path)) {
ZipEntry zipEntry = new ZipEntry(path.getFileName().toString());
zos.putNextEntry(zipEntry);
byte buffer[] = new byte[2048];
try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(path))) {
int bytesRead = 0;
while ((bytesRead = bis.read(buffer)) != -1) {
zos.write(buffer, 0, bytesRead);
}
} finally {
zos.closeEntry();
}
}
}
response().setHeader("Content-Type", "application/zip");
response().setHeader("Content-Disposition", "inline; filename=\"" + MimeUtility.encodeWord(toFilename) + "\"");
//I am confused here how to output the response of zip file i have created
//I tried with the `baos` and with `zos` streams but not working
return ok(baos.toByteArray());
} catch (IOException e) {
LOG.error("copy:" + e.getMessage(), e);
return ok(error(e.getMessage()).toJSONString());
}
return null;
}
我尝试使用 return ok(baos.toByteArray());
发送响应 我能够下载文件但是当我打开下载的文件时它给我错误 加载时发生错误存档
。
最佳答案
您需要关闭 zip 文件。添加所有条目后,执行:zos.close()
附带说明一下,我建议将 zip 文件写入磁盘而不是将其保存在内存缓冲区中。然后,您可以使用 return ok(File content, String filename)
将其内容发送到客户端。
关于java - 在 Play Framework 中下载动态创建的 zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43007656/