java-在play框架中下载动态创建的zip文件
作者:互联网
嗨,我正在尝试编写一个Play框架服务,我可以在其中下载多个文件.我即时创建了多个文件的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;
}
我尝试发送带有返回ok(baos.toByteArray())的响应;我能够下载文件,但是当我打开下载的文件时,它给我错误加载档案时发生错误.
解决方法:
您需要关闭zip文件.添加所有条目后,请执行:zos.close()
附带一提,我建议将zip文件写入磁盘,而不是将其保存在内存缓冲区中.然后,您可以使用return ok(文件内容,字符串文件名)将其内容发送到客户端.
标签:playframework,playframework-2-0,zip,stream,java 来源: https://codeday.me/bug/20191111/2020721.html