File download link in Tapestry

心已入冬 提交于 2019-12-12 02:08:43

问题


I have .tml file and its controller. There is a File variable in controller which represents an existing file from my server. I want to make this file downloadable by users, i.e. something like <a href="link-to-file">Download this file</a>. How could i do that in tapestry?

I want something like this:

//tml:
<t:file source="file">Download here</t:file>

//controller:
private File getFile() { ... }

回答1:


This is a simplified example which might achieve this for you.

in your tml

<a t:id="downloadLink">download</a>

in your java file

private File getFile() { ... }

@Component(id="downloadLink")
private ActionLink downloadLink;

@OnEvent(component="downloadLink")
private Object handleDownload(){
    final File getFile();
    final OutputStreamResponse response = new OutputStreamResponse() {

        public String getContentType() {
            return "application/pdf"; // or whatever content type your file is
        }

        public void prepareResponse(Response response) {
            response.setHeader ("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
        }

        @Override
        public void writeToStream(OutputStream out) throws IOException {
            try {
                InputStream in = new FileInputStream(file);
                IOUtils.copy(in,out);
                in.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }                   
        }
    };
    return response;
}


来源:https://stackoverflow.com/questions/29520097/file-download-link-in-tapestry

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!