【发布时间】:2017-08-17 20:57:33
【问题描述】:
您好,我正在尝试编写一个可以下载多个文件的播放框架服务。我即时创建了多个文件的 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()); 发送响应我能够下载文件,但是当我打开下载的文件时它给我错误An error occurred while loading the archive。
【问题讨论】:
-
什么不起作用?你检查过回复吗? ok 方法有几个选项来响应文件(文件,InputStream),如果你没有看到文件打开一个对话框来下载文件,你应该把它添加到你的响应中
application/x-download -
我的意思是我可以下载文件,但是当我打开它时,我的存档管理器游戏我读取文件时出错
-
我尝试使用
return ok(baos.toByteArray());发送响应,文件大小似乎还可以,但是当我打开下载的文件时,它给了我错误An error occured while loading the archive. -
那么问题不在于播放,您在压缩文件时可能做错了。
-
我有上面提到的邮政编码你觉得有什么问题吗?
标签: java playframework stream playframework-2.0 zip