使用 a-tag Play Framework 下载文件
Download File with an a-tag Play Framework
您好,我的问题是如何在 Play Framework 中处理下载
我的代码在 JAVA.
User user = User.find.byId(Long.parseLong(id));
File tempFile = null;
try {
tempFile = File.createTempFile(user.attachment_name, ".zip", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(user.attachment);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ok(tempFile);
但我不知道如何处理 return 在 HTML 视图上的反应 我可以用 link
下载它
您需要创建一个 Result
函数来下载内容。例如:
public static Result download(String id) throws IOException {
User user = User.find.byId(Long.parseLong(id));
File tempFile = null;
try {
tempFile = File.createTempFile(user.attachment_name, ".zip", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(user.attachment);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ok(tempFile);
}
路线:GET /download controllers.Application.download(id)
如果您有一个项目的下载 link,它的 href
应该是 href="@routes.Application.download(id)"
。您需要传递 id
(我相信您使用的是用户 ID)才能查看才能使用 id
您可能需要添加 ContentType
和 Content disposition
。
response().setContentType("application/octet-stream");
response().setHeader("Content-disposition", "attachment; filename=yourFileName.pdf");
其他选项是播放框架支持serving files。如果文件夹中已有文件,只需指定路径并让框架完成处理即可。
public Result index() {
return ok(new java.io.File("/tmp/fileToServe.pdf"));
}
您好,我的问题是如何在 Play Framework 中处理下载 我的代码在 JAVA.
User user = User.find.byId(Long.parseLong(id));
File tempFile = null;
try {
tempFile = File.createTempFile(user.attachment_name, ".zip", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(user.attachment);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ok(tempFile);
但我不知道如何处理 return 在 HTML 视图上的反应 我可以用 link
下载它您需要创建一个 Result
函数来下载内容。例如:
public static Result download(String id) throws IOException {
User user = User.find.byId(Long.parseLong(id));
File tempFile = null;
try {
tempFile = File.createTempFile(user.attachment_name, ".zip", null);
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(user.attachment);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ok(tempFile);
}
路线:GET /download controllers.Application.download(id)
如果您有一个项目的下载 link,它的 href
应该是 href="@routes.Application.download(id)"
。您需要传递 id
(我相信您使用的是用户 ID)才能查看才能使用 id
您可能需要添加 ContentType
和 Content disposition
。
response().setContentType("application/octet-stream");
response().setHeader("Content-disposition", "attachment; filename=yourFileName.pdf");
其他选项是播放框架支持serving files。如果文件夹中已有文件,只需指定路径并让框架完成处理即可。
public Result index() {
return ok(new java.io.File("/tmp/fileToServe.pdf"));
}