How to use Wicket's DownloadLink with a file generated on the fly?

后端 未结 2 1872
暖寄归人
暖寄归人 2020-11-28 12:55

DownloadLink is nice and handy for creating a button/link for downloading a file, along these lines:

add(new DownloadLink(\"downloadButton\", getReportFile()         


        
相关标签:
2条回答
  • 2020-11-28 13:19

    Use org.apache.wicket.markup.html.link.ResourceLink instead.

    0 讨论(0)
  • 2020-11-28 13:30

    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.

    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.

    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");
    

    Source code of DownloadLink.onClick()

    public void onClick()
    {
        final File file = (File)getModelObject();
                ...
        IResourceStream resourceStream = new FileResourceStream(
                new org.apache.wicket.util.file.File(file));
        getRequestCycle().setRequestTarget(.../* uses resourceStream */...);
    }
    
    0 讨论(0)
提交回复
热议问题