问题
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