如何将 Wicket 的 DownloadLink 与动态生成的文件一起使用? [英] How to use Wicket's DownloadLink with a file generated on the fly?
问题描述
DownloadLink
非常适合创建用于下载文件的按钮/链接,如下所示:
DownloadLink
is nice and handy for creating a button/link for downloading a file, along these lines:
add(new DownloadLink("downloadButton", getReportFile(), "report.pdf"));
和
<input type="button" wicket:id="downloadButton" value="Download" />
但是,我想仅在单击按钮/链接时触发文件的生成.换句话说,在点击时,我会调用一个方法来生成文件(在我们的例子中是 Pentaho 报告),将它放在一个临时位置并返回一个指向它的 File
.然后我会告诉 DownloadLink
使用那个 File
.问题是,这可能以某种方式吗?
However, I would like to trigger the generation of the file to download only when the button/link is clicked. In other words, upon click, I'd call a method that generates the file (a Pentaho report in our case), puts it in a temp place and returns a File
pointing to it. Then I'd tell the DownloadLink
to use that File
. Question is, is this possible somehow?
目前我们有类似下面的代码,它可以工作,但我对是否可以使用 DownloadLink
感兴趣.
Currently we have something like the code below, which works, but I'm interested in whether DownloadLink
could be used instead.
add(new Link<Void>("downloadButton") {
@Override
public void onClick() {
IResourceStream resourceStream = new AbstractResourceStreamWriter() {
@Override
public void write(OutputStream output) {
try {
reportService.generateReport(output, report);
} catch (IOException e) {
// ...
}
}
@Override
public String getContentType() {
return CONTENT_TYPE_PDF;
}
};
getRequestCycle()
.setRequestTarget(new ResourceStreamRequestTarget(resourceStream)
.setFileName("report.pdf"));
}
});
(Wicket 1.4.18,如果它有所不同.)
(Wicket 1.4.18, if it makes a difference.)
推荐答案
你不能使用以 Model
作为参数的构造函数吗?并使 Model
在其 getObject()
中生成 File
.LoadableDetachableModel
是一个不错的选择,因为 load()
以及文件生成只会被调用一次.
Can't you use the constructor that takes a Model
as argument? And make the Model
generate the File
in its getObject()
. A LoadableDetachableModel
is a good choice, given that load()
, and therefore file generation, will be invoked only once.
如果每次点击链接都新生成文件,使用DownloadLink.setDeleteAfterDownload(true)
确保文件在服务后自动删除.
If the file is to be freshly generated every time the link is clicked, use DownloadLink.setDeleteAfterDownload(true)
to ensure the File is automatically deleted once it is served.
我没有使用 1.4,但是 1.3 中的源代码显示 File
是通过 onClick() 中的
方法.getModelObject()
检索的Link
的
I don't use 1.4, but the source code in 1.3 shows that the File
is retrieved by means of getModelObject()
in the onClick()
method of the Link
.
IModel fileModel = new AbstractReadOnlyModel(){
public Object getObject() {
return generateFile();
}
};
DownloadLink link = new DownloadLink(linkId, fileModel, "report.pdf");
public void onClick()
{
final File file = (File)getModelObject();
...
IResourceStream resourceStream = new FileResourceStream(
new org.apache.wicket.util.file.File(file));
getRequestCycle().setRequestTarget(.../* uses resourceStream */...);
}
这篇关于如何将 Wicket 的 DownloadLink 与动态生成的文件一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!